import os
import json
import requests
from pathlib import Path

COMFYUI_URL = os.getenv("COMFYUI_URL", "http://127.0.0.1:8188").rstrip("/")
WORKFLOW_PATH = os.getenv("COMFYUI_WORKFLOW", "../comfy_workflows/wan_template.json")


def _load_workflow() -> dict:
    path = Path(WORKFLOW_PATH)
    if not path.exists():
        # fallback relative to project root
        path = Path(__file__).resolve().parents[3] / "comfy_workflows" / "wan_template.json"
    if not path.exists():
        raise FileNotFoundError("ComfyUI workflow JSON not found. Put your working workflow in comfy_workflows/wan_template.json")
    return json.loads(path.read_text(encoding="utf-8"))


def _inject_prompt(workflow: dict, req: dict) -> dict:
    """
    Generic mapper. You must edit node IDs after exporting your real ComfyUI workflow.
    Typical nodes contain inputs.text, inputs.width, inputs.height, inputs.seed, etc.
    """
    positive = req["prompt"]
    negative = req.get("negative_prompt", "")

    for node in workflow.values():
        inputs = node.get("inputs", {}) if isinstance(node, dict) else {}
        title = str(node.get("_meta", {}).get("title", "")).lower() if isinstance(node, dict) else ""
        class_type = str(node.get("class_type", "")).lower() if isinstance(node, dict) else ""

        if "positive" in title or "positive" in class_type:
            if "text" in inputs:
                inputs["text"] = positive
        if "negative" in title or "negative" in class_type:
            if "text" in inputs:
                inputs["text"] = negative
        for key in ["width", "height", "fps", "seed"]:
            if key in inputs and req.get(key) is not None:
                inputs[key] = req[key]

    return workflow


def submit_comfyui_job(req: dict, job_id: str) -> dict:
    workflow = _inject_prompt(_load_workflow(), req)
    payload = {"prompt": workflow, "client_id": job_id}
    res = requests.post(f"{COMFYUI_URL}/prompt", json=payload, timeout=30)
    res.raise_for_status()
    data = res.json()
    return {
        "status": "submitted",
        "video_url": None,
        "comfyui_prompt_id": data.get("prompt_id"),
        "note": "Job submitted to ComfyUI. Add polling/download logic after confirming your workflow output node.",
    }
