"""Hybrid 패턴 배경 생성 헬퍼 — 통합 경로 (Codex CLI / Gemini CLI / Satori) 한정.

외부 API 직접 호출 절대 금지:
- ❌ import openai, import anthropic, google.generativeai 직접 사용 금지
- ❌ HTTP requests로 api.openai.com, generativelanguage.googleapis.com 호출 금지
- ✅ subprocess.run(["codex", "exec", "--image-out", path, prompt]) — H3
- ✅ subprocess.run(["gemini", "-p", prompt]) — H1, H2
- ✅ CLI 부재 시 placeholder 그라디언트로 graceful fallback

IDS Phase 1 §3.2.1 / §0.2 Hybrid Pattern Standard 준수.
"""

from __future__ import annotations

import shutil
import subprocess
from pathlib import Path


def generate_gemini_background(
    prompt: str,
    output_path: Path | str,
    *,
    style: str = "photoreal",
    timeout: int = 180,
) -> Path | None:
    """Gemini CLI 통합 경로로 배경 이미지를 생성한다.

    Args:
        prompt: 영문 prompt (한글 텍스트는 별도 Satori 오버레이로 처리).
        output_path: 출력 이미지 경로.
        style: "photoreal" | "illustration" 등.
        timeout: CLI timeout (초).

    Returns:
        생성된 이미지 경로 또는 None (CLI 부재/실패 시).
    """
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    gemini_bin = shutil.which("gemini")
    if gemini_bin is None:
        return None

    full_prompt = f"{style} style background image, no text, no letters: {prompt}"
    try:
        subprocess.run(
            [gemini_bin, "-p", full_prompt, "--image-out", str(output_path)],
            check=True,
            capture_output=True,
            timeout=timeout,
        )
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
        return None

    return output_path if output_path.exists() else None


def generate_codex_gpt_background(
    prompt: str,
    output_path: Path | str,
    *,
    timeout: int = 180,
) -> Path | None:
    """Codex CLI 통합 경로로 GPT image 배경을 생성한다.

    `codex exec --image-out path.png "<prompt>"` 형식. 외부 OpenAI API 직접 호출
    절대 금지 — 반드시 codex CLI 경유.

    Args:
        prompt: 영문 prompt.
        output_path: 출력 이미지 경로.
        timeout: CLI timeout (초).

    Returns:
        생성된 이미지 경로 또는 None (CLI 부재/실패 시).
    """
    output_path = Path(output_path)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    codex_bin = shutil.which("codex")
    if codex_bin is None:
        return None

    try:
        subprocess.run(
            [codex_bin, "exec", "--image-out", str(output_path), prompt],
            check=True,
            capture_output=True,
            timeout=timeout,
        )
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
        return None

    return output_path if output_path.exists() else None


def build_background_layer_html(
    background_path: Path | str | None,
    *,
    width: int,
    height: int,
    fallback_gradient: str | None = None,
) -> str:
    """배경 레이어 HTML을 생성한다.

    Args:
        background_path: 이미지 파일 경로 (None이면 fallback_gradient 사용).
        width: 폭.
        height: 높이.
        fallback_gradient: 배경 부재 시 적용할 CSS gradient.

    Returns:
        Satori-호환 background div HTML.
    """
    base_style = (
        f"position:absolute; top:0; left:0; width:{width}px; height:{height}px; "
        "display:flex;"
    )

    if background_path is not None and Path(background_path).exists():
        # file:// URI로 임베드 (Satori는 fetch 가능)
        uri = Path(background_path).resolve().as_uri()
        return (
            f'<div style="{base_style} background-image:url({uri}); '
            f'background-size:cover; background-position:center;"></div>'
        )

    gradient = fallback_gradient or (
        "linear-gradient(135deg, #1a1f3a 0%, #2d2050 50%, #4a2a6e 100%)"
    )
    return f'<div style="{base_style} background:{gradient};"></div>'


def default_gradient(theme: str = "navy") -> str:
    """그라디언트 프리셋. (H4, fallback 공통)

    Args:
        theme: "navy" | "warm" | "mint" | "rose" | "mono".

    Returns:
        CSS linear-gradient 문자열.
    """
    presets: dict[str, str] = {
        "navy": "linear-gradient(135deg, #0f1729 0%, #1e2952 50%, #2a3a7a 100%)",
        "warm": "linear-gradient(135deg, #2a1810 0%, #5c2a1a 50%, #a04020 100%)",
        "mint": "linear-gradient(135deg, #0a2820 0%, #1a4a3c 50%, #2d7a64 100%)",
        "rose": "linear-gradient(135deg, #2a1020 0%, #5a1e3e 50%, #a83a6e 100%)",
        "mono": "linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #2a2a2a 100%)",
    }
    return presets.get(theme, presets["navy"])
