"""FikoYT ControlNet Union Apply — Tek CN-Union modeli, control_type seçilebilir."""
import os

try:
    import folder_paths
    import comfy.controlnet
    import comfy.sd
    from nodes import ControlNetApplyAdvanced
except ImportError:
    folder_paths = None
    comfy = None
    ControlNetApplyAdvanced = None

from ..core import ensure_model, get_models_dir


# Xinsir CN-Union — SDXL için. Flux için ayrı Shakker-Labs CN-Union.
CN_UNION_PRESETS = {
    "SDXL Union ProMax (Xinsir)": {
        "repo": "xinsir/controlnet-union-sdxl-1.0",
        "file": "diffusion_pytorch_model_promax.safetensors",
        "subdir": "controlnet",
    },
    "Flux Union (Shakker-Labs)": {
        "repo": "Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro",
        "file": "diffusion_pytorch_model.safetensors",
        "subdir": "controlnet",
    },
}

CONTROL_TYPES = [
    "canny", "tile", "depth", "blur", "pose", "openpose",
    "scribble", "normal", "segment", "lineart", "softedge", "anime_lineart",
]


class FikoYTCNUnionApply:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "positive": ("CONDITIONING",),
                "negative": ("CONDITIONING",),
                "control_image": ("IMAGE",),
                "vae": ("VAE",),
                "preset": (list(CN_UNION_PRESETS.keys()), {"default": "SDXL Union ProMax (Xinsir)"}),
                "control_type":  (CONTROL_TYPES, {"default": "canny"}),
                "strength":      ("FLOAT", {"default": 1.0, "min": 0.0, "max": 2.0, "step": 0.05}),
                "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
                "end_percent":   ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
                "auto_download": ("BOOLEAN", {"default": True}),
            }
        }

    RETURN_TYPES = ("CONDITIONING", "CONDITIONING")
    RETURN_NAMES = ("positive", "negative")
    FUNCTION = "apply"
    CATEGORY = "FikoYT/image"

    def apply(self, positive, negative, control_image, vae,
              preset, control_type, strength, start_percent, end_percent, auto_download):
        meta = CN_UNION_PRESETS[preset]
        cn_dir = get_models_dir(meta["subdir"])
        cn_path = os.path.join(cn_dir, meta["file"])

        if not os.path.isfile(cn_path):
            if auto_download:
                cn_path = ensure_model(meta["repo"], meta["file"], meta["subdir"])
            else:
                raise FileNotFoundError(
                    f"CN-Union modeli bulunamadı: {cn_path}\nauto_download=True yapın."
                )

        if comfy is None or ControlNetApplyAdvanced is None:
            raise RuntimeError("ComfyUI çekirdeği yok — ComfyUI ortamında çalıştırın.")

        controlnet = comfy.controlnet.load_controlnet(cn_path)

        # CN-Union union_type tagging — modelin desteklediği yerlerde
        if hasattr(controlnet, "set_extra_arg"):
            try:
                controlnet.set_extra_arg("control_type", control_type)
            except Exception:
                pass

        out = ControlNetApplyAdvanced().apply_controlnet(
            positive=positive,
            negative=negative,
            control_net=controlnet,
            image=control_image,
            strength=strength,
            start_percent=start_percent,
            end_percent=end_percent,
            vae=vae,
        )
        if isinstance(out, tuple) and len(out) >= 2:
            return (out[0], out[1])
        return (positive, negative)


NODE_CLASS_MAPPINGS = {"FikoYTCNUnionApply": FikoYTCNUnionApply}
NODE_DISPLAY_NAME_MAPPINGS = {"FikoYTCNUnionApply": "FikoYT • ControlNet Union Apply"}
