"""v4-hybrid 배경 이미지 생성 스크립트.

gcloud access token으로 Gemini API를 직접 호출하여
텍스트 없는 배경 이미지 3장(bg_A, bg_B, bg_C)을 생성합니다.
"""

import base64
import subprocess
import time
from datetime import datetime
from pathlib import Path

import requests

OUTPUT_DIR = Path("/home/jay/workspace/tools/ai-image-gen/output/v4-hybrid")
ERRORS_LOG = OUTPUT_DIR / "errors.log"

MODEL_ID = "gemini-3.1-flash-image-preview"
GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta"
GEMINI_SCOPE = "https://www.googleapis.com/auth/generative-language"

SCENARIOS = {
    "A": (
        "Premium corporate office environment. "
        "100th-floor Seoul panoramic view through floor-to-ceiling windows. "
        "Golden hour lighting, warm volumetric rays. Navy and gold color scheme. "
        "Blurred background suitable for text overlay. "
        "No text, no people, no watermark. 1080x1080 square format."
    ),
    "B": (
        "Luxury private consultation room atmosphere. "
        "Dark walnut bookshelf, mahogany desk, brass lamp. "
        "Warm amber lighting. Shallow depth of field, dreamy bokeh. "
        "No text, no people. 1080x1080."
    ),
    "C": (
        "Cinematic corridor scene. "
        "Dark corporate hallway with golden light streaming through open door at the end. "
        "Volumetric god-rays, dust particles. Teal and orange color grade. "
        "No text, no people. 1080x1080."
    ),
}


def get_gcloud_access_token() -> str:
    result = subprocess.run(
        ["gcloud", "auth", "print-access-token", f"--scopes={GEMINI_SCOPE}"],
        capture_output=True,
        text=True,
        check=True,
    )
    token = result.stdout.strip()
    if not token:
        raise RuntimeError("gcloud auth print-access-token이 빈 토큰을 반환했습니다.")
    return token


def log_error(message: str) -> None:
    timestamp = datetime.now().isoformat()
    with open(ERRORS_LOG, "a", encoding="utf-8") as f:
        f.write(f"[{timestamp}] {message}\n")
    print(f"[ERROR] {message}")


def generate_image(token: str, scenario: str, prompt: str) -> dict:
    url = f"{GEMINI_API_BASE}/models/{MODEL_ID}:generateContent"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
    }
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {"responseModalities": ["IMAGE", "TEXT"]},
    }

    print(f"[시나리오 {scenario}] 요청 중... (모델: {MODEL_ID})")
    start = time.time()

    response = requests.post(url, headers=headers, json=payload, timeout=180)
    response.raise_for_status()
    elapsed = time.time() - start

    data = response.json()
    candidates = data.get("candidates", [])
    if not candidates:
        import json
        raise RuntimeError(f"candidates 없음. 응답: {json.dumps(data)[:300]}")

    parts = candidates[0].get("content", {}).get("parts", [])
    image_part = next((p for p in parts if "inlineData" in p), None)
    if image_part is None:
        text_parts = [p.get("text", "") for p in parts if "text" in p]
        raise RuntimeError(f"이미지 데이터 없음. 텍스트 파트: {text_parts[:2]}")

    mime_type = image_part["inlineData"].get("mimeType", "image/jpeg")
    image_bytes = base64.b64decode(image_part["inlineData"]["data"])

    ext = ".jpg" if "jpeg" in mime_type else ".png"
    output_path = OUTPUT_DIR / f"bg_{scenario}{ext}"
    output_path.write_bytes(image_bytes)

    size = output_path.stat().st_size
    print(f"[시나리오 {scenario}] 완료: {output_path.name} ({size:,} bytes, {elapsed:.1f}초, mime={mime_type})")

    return {
        "scenario": scenario,
        "filepath": str(output_path),
        "filename": output_path.name,
        "file_size_bytes": size,
        "mime_type": mime_type,
        "time_seconds": round(elapsed, 2),
        "error": None,
    }


def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    print("=" * 60)
    print("v4-hybrid 배경 이미지 생성 시작")
    print(f"모델: {MODEL_ID}")
    print(f"출력 디렉토리: {OUTPUT_DIR}")
    print("=" * 60)

    print("\n[인증] gcloud access token 획득 중...")
    try:
        token = get_gcloud_access_token()
        print(f"[인증] 토큰 획득 성공 (길이: {len(token)} chars)")
    except Exception as e:
        log_error(f"토큰 획득 실패: {type(e).__name__}: {e}")
        raise SystemExit(1) from e

    results = []

    for scenario in ["A", "B", "C"]:
        print(f"\n[{scenario}] 처리 중...")
        try:
            result = generate_image(token, scenario, SCENARIOS[scenario])
        except requests.HTTPError as e:
            error_msg = f"시나리오 {scenario} HTTP 오류: {e.response.status_code} - {e.response.text[:500]}"
            log_error(error_msg)
            result = {"scenario": scenario, "error": error_msg, "filepath": None, "filename": None,
                      "file_size_bytes": None, "mime_type": None, "time_seconds": None}
        except Exception as e:
            error_msg = f"시나리오 {scenario} 오류: {type(e).__name__}: {e}"
            log_error(error_msg)
            result = {"scenario": scenario, "error": error_msg, "filepath": None, "filename": None,
                      "file_size_bytes": None, "mime_type": None, "time_seconds": None}
        results.append(result)

    print("\n" + "=" * 60)
    print("결과 요약")
    print("=" * 60)
    success = sum(1 for r in results if r["error"] is None)
    print(f"성공: {success}/3, 실패: {3 - success}/3")
    for r in results:
        status = "OK" if r["error"] is None else "FAIL"
        size_str = f"{r['file_size_bytes']:,} bytes" if r["file_size_bytes"] else "N/A"
        t_str = f"{r['time_seconds']:.1f}초" if r["time_seconds"] else "N/A"
        print(f"  [{r['scenario']}] {status} | {r.get('filename','N/A')} | {size_str} | {t_str}")
        if r["error"]:
            print(f"         ERROR: {r['error']}")

    if ERRORS_LOG.exists():
        print(f"\n에러 로그: {ERRORS_LOG}")


if __name__ == "__main__":
    main()
