from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Dict, Any
import subprocess
import json
import glob
import os

# IMPORT YOUR EXISTING LOGIC
from fetch_land_data import transform_row

app = FastAPI(title="AI Land Pipeline API")


# ==============================
# REQUEST MODEL
# ==============================
class PipelineRequest(BaseModel):
    raw_data: List[Dict[str, Any]]


# ==============================
# API ENDPOINT
# ==============================
@app.post("/land_check")
def run_pipeline(req: PipelineRequest):

    try:

        # =========================================
        # STEP 1: SAME TRANSFORM LOGIC
        # =========================================
        transformed_data = [
            transform_row(row)
            for row in req.raw_data
        ]

        # =========================================
        # STEP 2: SAVE SAME FILE
        # =========================================
        with open("formatted_output.json", "w", encoding="utf-8") as f:

            json.dump(
                transformed_data,
                f,
                indent=2,
                ensure_ascii=False
            )

        print("✅ formatted_output.json created")

        # =========================================
        # STEP 3: RUN SAME MATCH PIPELINE
        # =========================================
        match_result = subprocess.run(
            ["python3", "match_pipeline.py"],
            capture_output=True,
            text=True
        )

        if match_result.returncode != 0:

            raise HTTPException(
                status_code=500,
                detail=match_result.stderr
            )

        # =========================================
        # STEP 4: FIND RESULT FILE
        # =========================================
        grouped_files = glob.glob("grouped_result_*.json")

        if not grouped_files:

            raise HTTPException(
                status_code=500,
                detail="No grouped result file found"
            )

        latest_file = max(grouped_files, key=os.path.getctime)

        # =========================================
        # STEP 5: PUSH STATUS
        # =========================================
        push_result = subprocess.run(
            [
                "python3",
                "push_ai_status.py",
                latest_file
            ],
            capture_output=True,
            text=True
        )

        if push_result.returncode != 0:

            raise HTTPException(
                status_code=500,
                detail=push_result.stderr
            )

        # =========================================
        # STEP 6: LOAD FINAL RESULT
        # =========================================
        with open(latest_file, "r", encoding="utf-8") as f:
            final_result = json.load(f)

        # =========================================
        # CHECK FINAL STATUS
        # =========================================
        is_success = True

        for _, item in final_result.items():

            if item.get("status") == "REJECTED":
                is_success = False
            break
    

        # =========================================
        # FINAL RESPONSE
        # =========================================
        return {
            "success": is_success,
            "grouped_result_file": latest_file,
            "data": final_result
        }

    except Exception as e:

        raise HTTPException(
            status_code=500,
            detail=str(e)
        )