"""슬라이드 3 (해결책 제시) 이미지 생성 스크립트."""

import sys
import base64
import requests
import time
import os

sys.path.insert(0, '/home/jay/workspace/tools/ai-image-gen')
import gcloud_auth

PROMPT = (
    "Create a vertical card news slide image (portrait orientation, 4:5 ratio) "
    "for a Korean insurance sales team recruiting campaign — Slide 3: Solution Reveal.\n\n"
    "SCENE: A confident Korean professional (insurance consultant, 30s, wearing smart business casual — "
    "dark navy blazer over light shirt) stands at the center-foreground, facing slightly left with a bright "
    "smile and confident posture. Behind and around them float multiple glowing digital screens, holographic "
    "AI dashboards, smartphone interfaces, tablet UI panels, notification bell icons, and data flow "
    "visualizations. The character feels empowered as the technology works autonomously around them. "
    "It looks like the systems are doing the selling for them.\n\n"
    "VISUAL STYLE: High-quality digital illustration / semi-realistic AI art style. NOT stock photo. "
    "Clean, modern Korean webtoon-influenced but polished. Strong cinematic composition.\n\n"
    "BACKGROUND: Dark navy (#001133) at the very bottom smoothly transitioning to bright electric blue "
    "(#0044CC) in the middle, then to bright cyan/sky blue (#00CCFF) and near-white at the top. "
    "Glowing neon light trails. Feels like a sunrise or breakthrough moment — dark-to-bright transition. "
    "Volumetric light rays emanating from the upper center.\n\n"
    "TEXT ELEMENTS (render these exactly):\n"
    "1. TOP AREA — Large bold Korean text: 시스템이 대신 팔아주는 곳\n"
    "   Style: Heavy white bold sans-serif font, with subtle cyan glow/shadow. Very prominent.\n\n"
    "2. MIDDLE AREA — Five keyword badge chips in a horizontal row:\n"
    "   Consulting Logic | Naver Pipeline | AI Automation | Authority Brand | IT Work-Flow\n"
    "   Style: Glowing pill-shaped badges with white text on semi-transparent dark blue backgrounds.\n\n"
    "3. BOTTOM TEXT — Korean subtitle in smaller white text: 5대 AI 영업시스템을 직접 운영\n\n"
    "4. BOTTOM RIGHT CORNER — Small branding text: 서울대보험쌤 x 티오피사업단\n\n"
    "COLOR PALETTE: Electric blue (#0066FF), bright cyan (#00D4FF), deep navy (#001133), white (#FFFFFF). "
    "Glowing neon accents. Tech/AI aesthetic.\n\n"
    "LIGHTING: Volumetric god-rays from top center. Subject lit by cool blue-white fill light. "
    "Glowing screens cast blue-cyan light on the character's face.\n\n"
    "MOOD: Discovery moment, breakthrough solution found, empowering, futuristic, hopeful. "
    "The feeling of the system working for you.\n\n"
    "COMPOSITION: Rule of thirds. Character in lower-center. Digital elements fill upper area. "
    "Text clearly overlaid across zones.\n\n"
    "STYLE: Samsung Galaxy / Korean fintech app promotional illustration. Cinematic but clean. "
    "No watermarks. No clipart. No stock photo aesthetic.\n\n"
    "ASPECT: Tall portrait format (4:5 ratio, 1080x1350 equivalent), optimized for mobile."
)


def get_token_with_scope():
    """generative-language 스코프로 gcloud 토큰 획득."""
    import subprocess
    result = subprocess.run(
        ['gcloud', 'auth', 'print-access-token',
         '--scopes=https://www.googleapis.com/auth/generative-language'],
        capture_output=True, text=True, check=True
    )
    token = result.stdout.strip()
    if not token:
        raise RuntimeError("빈 토큰 반환")
    return token


def main():
    print("인증 토큰 획득 중 (generative-language scope)...")
    token = get_token_with_scope()
    print(f"토큰 획득 성공: {len(token)} chars")

    url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
    }
    payload = {
        'contents': [{'parts': [{'text': PROMPT}]}],
        'generationConfig': {
            'responseModalities': ['IMAGE', 'TEXT'],
            'temperature': 1.0
        }
    }

    print("이미지 생성 요청 중... (약 25-60초 소요)")
    start = time.time()
    response = requests.post(url, headers=headers, json=payload, timeout=300)
    elapsed = time.time() - start
    print(f"응답 수신: {elapsed:.1f}초, 상태코드: {response.status_code}")

    if response.status_code != 200:
        print("오류 응답:", response.text[:500])
        sys.exit(1)

    data = response.json()
    candidates = data.get('candidates', [])
    if not candidates:
        print("candidates 없음:", str(data)[:300])
        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("이미지 없음. 텍스트:", text_parts)
        sys.exit(1)

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

    os.makedirs('/home/jay/.cokacdir/workspace/7A90EE10', exist_ok=True)

    # 확장자 결정
    if 'jpeg' in mime_type:
        ext = '.jpg'
        target = '/home/jay/.cokacdir/workspace/7A90EE10/slide3-solution.png'
    else:
        ext = '.png'
        target = '/home/jay/.cokacdir/workspace/7A90EE10/slide3-solution.png'

    actual_path = '/home/jay/.cokacdir/workspace/7A90EE10/slide3-solution' + ext

    with open(actual_path, 'wb') as f:
        f.write(image_bytes)

    size = os.path.getsize(actual_path)
    print(f"저장 완료: {actual_path}")
    print(f"파일 크기: {size:,} bytes ({size/1024:.1f} KB)")
    print(f"MIME 타입: {mime_type}")

    # .png로 요청했으나 .jpg로 저장된 경우 복사
    if actual_path != target and ext == '.jpg':
        import shutil
        shutil.copy2(actual_path, target)
        print(f"PNG 경로로도 복사: {target}")

    return actual_path


if __name__ == '__main__':
    main()
