#!/usr/bin/env python3
"""컨셉 #04 — 현실-판타지 경계 해체 하이브리드 이미지 생성 스크립트"""

import sys
import base64
import time
from pathlib import Path

# ai-image-gen 모듈 경로 추가
sys.path.insert(0, "/home/jay/workspace/tools/ai-image-gen")

import gcloud_auth
import requests
from playwright.sync_api import sync_playwright

OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/04-reality-fantasy")
BG_PATH = OUTPUT_DIR / "bg.jpg"
TEMPLATE_PATH = OUTPUT_DIR / "template.html"
OUTPUT_PATH = OUTPUT_DIR / "sample.png"

GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"

BG_PROMPT = (
    "A tired Korean office worker in dark business suit sitting at a desk late at night, "
    "city office background with glowing screens, slightly desaturated and cold-toned, "
    "cinematic mood, photorealistic, soft focus background, front-facing portrait, "
    "1080x1080 square composition, moody atmospheric lighting"
)


def generate_background(token: str) -> Path:
    """Gemini API로 배경 이미지를 생성하고 저장합니다."""
    for model_id in ["gemini-2.0-flash-preview-image-generation", "imagen-3.0-generate-002", "gemini-3-pro-image-preview", "gemini-3.1-flash-image-preview"]:
        print(f"[배경] 모델 시도: {model_id}")
        url = f"{GEMINI_API_BASE}/models/{model_id}:generateContent"
        headers = {
            "Authorization": f"Bearer {token}",
            "Content-Type": "application/json",
        }

        if "imagen" in model_id:
            # Imagen API 포맷
            url = f"{GEMINI_API_BASE}/models/{model_id}:predict"
            payload = {
                "instances": [{"prompt": BG_PROMPT}],
                "parameters": {
                    "sampleCount": 1,
                    "aspectRatio": "1:1",
                },
            }
        else:
            payload = {
                "contents": [{"parts": [{"text": BG_PROMPT}]}],
                "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
            }

        try:
            resp = requests.post(url, headers=headers, json=payload, timeout=120)
            if resp.status_code in (403, 404):
                print(f"  → HTTP {resp.status_code}, 다음 모델 시도...")
                continue
            resp.raise_for_status()
            data = resp.json()

            # 이미지 추출
            image_b64 = None
            mime_type = "image/jpeg"

            if "imagen" in model_id:
                # Imagen 응답 구조
                predictions = data.get("predictions", [])
                if predictions:
                    pred = predictions[0]
                    if "bytesBase64Encoded" in pred:
                        image_b64 = pred["bytesBase64Encoded"]
                        mime_type = pred.get("mimeType", "image/png")
            else:
                # Gemini 응답 구조
                candidates = data.get("candidates", [])
                if candidates:
                    parts = candidates[0].get("content", {}).get("parts", [])
                    for part in parts:
                        if "inlineData" in part:
                            image_b64 = part["inlineData"]["data"]
                            mime_type = part["inlineData"].get("mimeType", "image/jpeg")
                            break

            if not image_b64:
                print(f"  → 이미지 데이터 없음, 다음 모델 시도...")
                continue

            image_bytes = base64.b64decode(image_b64)
            ext = ".png" if "png" in mime_type else ".jpg"
            save_path = OUTPUT_DIR / f"bg{ext}"
            save_path.write_bytes(image_bytes)
            print(f"[배경] 저장 완료: {save_path} ({len(image_bytes):,} bytes)")
            return save_path

        except requests.HTTPError as e:
            print(f"  → HTTP 오류: {e.response.status_code} - {e.response.text[:200]}")
            continue
        except Exception as e:
            print(f"  → 오류: {type(e).__name__}: {e}")
            continue

    raise RuntimeError("모든 Gemini 모델에서 배경 생성 실패")


def capture_html(bg_path: Path) -> None:
    """Playwright로 HTML 템플릿을 캡처하여 최종 이미지를 저장합니다."""
    print(f"[HTML] 캡처 시작: {TEMPLATE_PATH}")
    template_url = f"file://{TEMPLATE_PATH.resolve()}"
    bg_file_url = f"file://{bg_path.resolve()}"

    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            page = browser.new_page(viewport={"width": 1080, "height": 1080})
            page.goto(template_url, wait_until="networkidle")

            # BG 이미지 경로 주입
            page.evaluate(f"""() => {{
                window.BG_IMAGE_PATH = "{bg_file_url}";
                const bgEl = document.getElementById('bg');
                if (bgEl) {{
                    bgEl.style.setProperty('--bg-url', 'url("{bg_file_url}")');
                }}
            }}""")

            # 폰트 및 렌더링 대기
            page.wait_for_timeout(2500)

            OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
            page.screenshot(path=str(OUTPUT_PATH), type="png")
            print(f"[HTML] 캡처 완료: {OUTPUT_PATH}")
        finally:
            browser.close()


def main():
    print("=" * 60)
    print("컨셉 #04 현실-판타지 경계 해체 생성 시작")
    print("=" * 60)

    # 1. 인증 토큰 획득
    print("\n[인증] SA 토큰 획득 중...")
    token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
    print(f"[인증] 토큰 획득 성공 (길이: {len(token)} chars)")

    # 2. 배경 이미지 생성
    print("\n[1단계] Gemini 배경 이미지 생성...")
    bg_path = generate_background(token)

    # bg.jpg 심볼릭 링크 또는 복사 (파일명 통일)
    if bg_path != BG_PATH and bg_path.exists():
        import shutil
        if BG_PATH.exists():
            BG_PATH.unlink()
        # 확장자에 따라 실제 경로 사용
        final_bg = bg_path
    else:
        final_bg = bg_path

    # 3. HTML + Playwright 캡처
    print("\n[2단계] HTML 오버레이 캡처...")
    capture_html(final_bg)

    # 4. 결과 보고
    size_kb = OUTPUT_PATH.stat().st_size / 1024
    print(f"\n{'=' * 60}")
    print("생성 완료!")
    print(f"  배경:  {final_bg}")
    print(f"  HTML:  {TEMPLATE_PATH}")
    print(f"  최종:  {OUTPUT_PATH} ({size_kb:.0f} KB)")
    print("=" * 60)


if __name__ == "__main__":
    main()
