"""컨셉 #41 당신 같은 사람 (Unedited Reality Portrait) 인물 이미지 생성."""

from __future__ import annotations

import base64
import json
import subprocess
import sys
import time
from pathlib import Path

import requests

OUTPUT_DIR = Path("/home/jay/workspace/output/meta-ads/concept-catalog/41-cannes-unedited-reality")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

MODEL_ID = "gemini-3-pro-image-preview"
FALLBACK_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"

PROMPT = (
    "A casual unposed photograph of a Korean man in his late 40s to early 50s. "
    "He is wearing everyday clothing a plaid flannel shirt. "
    "He is sitting at a cozy coffee shop with a cup of coffee. "
    "The photo looks like it was taken by a friend with a smartphone slightly imperfect framing, "
    "natural ambient lighting warm afternoon window light, no studio setup. "
    "His expression is genuine relaxed contentment, a real smile not a forced pose. "
    "Background is softly blurred shallow depth of field, recognizable but not prominent. "
    "Photo texture slightly grainy, warm color tones, documentary snapshot photography style. "
    "1080x1080 square format, realistic, no AI-perfect skin, natural imperfections welcome. "
    "No text, no graphics, no overlays."
)


def get_token() -> str:
    """gcloud CLI로 액세스 토큰 획득."""
    result = subprocess.run(
        ["gcloud", "auth", "print-access-token",
         "--scopes=https://www.googleapis.com/auth/generative-language"],
        capture_output=True, text=True, timeout=30
    )
    if result.returncode != 0:
        raise RuntimeError(f"gcloud 토큰 획득 실패: {result.stderr}")
    return result.stdout.strip()


def call_gemini(token: str, model_id: str, prompt: str) -> requests.Response:
    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"],
            "temperature": 1.0
        }
    }
    return requests.post(url, headers=headers, json=payload, timeout=300)


def main() -> None:
    print("=== 컨셉 #41 인물 이미지 생성 ===")
    print(f"출력 디렉토리: {OUTPUT_DIR}")

    # 토큰 획득 (SA 먼저 시도, 실패 시 gcloud CLI)
    try:
        sys.path.insert(0, "/home/jay/workspace/tools/ai-image-gen")
        import gcloud_auth
        token = gcloud_auth.get_service_account_token(GEMINI_SCOPE)
        print(f"SA 토큰 획득 성공 (길이: {len(token)})")
    except Exception as e:
        print(f"SA 토큰 실패: {e}, gcloud CLI 시도...")
        token = get_token()
        print(f"gcloud CLI 토큰 획득 성공 (길이: {len(token)})")

    # 이미지 생성
    start = time.time()
    print(f"모델: {MODEL_ID} 호출 중...")
    response = call_gemini(token, MODEL_ID, PROMPT)

    if response.status_code in (403, 404):
        print(f"Pro 모델 실패 ({response.status_code}), fallback: {FALLBACK_MODEL_ID}")
        response = call_gemini(token, FALLBACK_MODEL_ID, PROMPT)

    elapsed = time.time() - start

    if response.status_code != 200:
        print(f"API 오류 {response.status_code}: {response.text[:500]}")
        sys.exit(1)

    data = response.json()
    candidates = data.get("candidates", [])
    if not candidates:
        print(f"candidates 없음. 응답: {json.dumps(data)[:500]}")
        sys.exit(1)

    parts = candidates[0].get("content", {}).get("parts", [])
    image_part = None
    for part in parts:
        if "inlineData" in part:
            image_part = part
            break

    if image_part is None:
        text_parts = [p.get("text", "") for p in parts if "text" in p]
        print(f"이미지 없음. 텍스트: {text_parts}")
        sys.exit(1)

    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"person-background{ext}"
    output_path.write_bytes(image_bytes)

    size = output_path.stat().st_size
    print(f"저장 완료: {output_path}")
    print(f"파일 크기: {size:,} bytes, 소요: {elapsed:.1f}초, MIME: {mime_type}")

    # 메타데이터 저장
    meta = {
        "concept": "41-cannes-unedited-reality",
        "prompt": PROMPT,
        "model": MODEL_ID,
        "output": str(output_path),
        "size_bytes": size,
        "time_seconds": round(elapsed, 2),
        "mime_type": mime_type,
    }
    (OUTPUT_DIR / "generation-meta.json").write_text(
        json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8"
    )
    print(f"메타데이터: {OUTPUT_DIR / 'generation-meta.json'}")


if __name__ == "__main__":
    main()
