"""
Golpo Python SDK — Full Parameter Test Suite
=============================================
Uses create_podcast / create_video directly (blocking — polls internally).

Usage:
    pip install -e .
    python test_all_params.py
"""

import sys
import time
import traceback

from golpo import Golpo

# ── Configuration ───────────────────────────────────────────────────────────────
API_KEY = "5XKDG3tw4v8Fafv9PTcog3kVnU7hit3W4Zw1s4nE"  # <-- paste your Golpo API key here
BASE_URL = "https://staging-api.golpoai.com"

# Local test assets
TEST_DIR = r"D:\GOLPO AI\Testing Resources"
LOGO_IMAGE = rf"{TEST_DIR}\prism_logo.png"
LEETCODE_IMAGE = rf"{TEST_DIR}\Leedcode easy pbm.png"
SAMPLE_VIDEO = rf"{TEST_DIR}\real.mp4"
SAMPLE_AUDIO = rf"{TEST_DIR}\9_16.mp4"
SSH_VIDEO = rf"{TEST_DIR}\ssh.mp4"

client = Golpo(API_KEY, BASE_URL)

# ── Podcast test cases (2) ──────────────────────────────────────────────────────
PODCAST_TESTS = [
    {
        "name": "P01 — basic solo-female podcast (1 min)",
        "prompt": "How AI assistants like Siri and Alexa are reshaping daily routines",
        "opts": {
            "style": "solo-female",
            "tts_model": "accurate",
            "output_volume": 1.0,
            "bg_music": "engaging",
            "timing": "1",
        },
    },
    {
        "name": "P02 — conversational podcast",
        "prompt": "The great debate between terraforming Mars versus saving our own planet",
        "opts": {
            "style": "conversational",
            "personality_1": "Enthusiastic tech journalist",
            "personality_2": "Skeptical academic professor",
            "add_music": True,
            "bg_music": "lofi",
            "timing": "0.25",
        },
    },
]

# ── Video test cases (18) — COMMENTED OUT FOR NOW ───────────────────────────────
# VIDEO_TESTS = [
#     {
#         "name": "V01 — basic color video",
#         "prompt": "Why honey never spoils and the science behind food preservation",
#         "opts": {
#             "use_color": True,
#             "style": "solo-female",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V02 — video with logo",
#         "prompt": "How solar panels convert sunlight into usable electricity",
#         "opts": {
#             "use_color": True,
#             "logo": LOGO_IMAGE,
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V03 — own narration (audio mode)",
#         "prompt": "Create a visual explainer based on the provided audio narration",
#         "opts": {
#             "use_color": True,
#             "audio_clip": SAMPLE_AUDIO,
#             "own_narration_video_mode": "audio",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V04 — own narration (pip mode)",
#         "prompt": "Explain the content from the provided video with picture-in-picture overlay",
#         "opts": {
#             "use_color": True,
#             "audio_clip": SAMPLE_VIDEO,
#             "own_narration_video_mode": "pip",
#             "own_narration_pip_position": "right-bottom",
#             "timing": "2",
#         },
#     },
#     {
#         "name": "V05 — 2.0 style + neon",
#         "prompt": "How neon lights work and why cities glow at night",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "neon",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V06 — 2.0 style + whiteboard",
#         "prompt": "Newton's three laws of motion explained with everyday examples",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "whiteboard",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V07 — 2.0 style + modern_minimal",
#         "prompt": "The basics of blockchain technology in simple terms",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "modern_minimal",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V08 — 2.0 style + playful",
#         "prompt": "Why octopuses are considered the smartest invertebrates in the ocean",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "playful",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V09 — 2.0 style + technical",
#         "prompt": "How TCP/IP works and why it powers the entire internet",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "technical",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V10 — 2.0 style + editorial",
#         "prompt": "The rise and fall of Kodak and lessons in corporate innovation",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "editorial",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V11 — sketch classic",
#         "prompt": "How photosynthesis works inside a leaf",
#         "opts": {
#             "use_color": True,
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V12 — sketch formal",
#         "prompt": "The anatomy of a volcano and how eruptions happen",
#         "opts": {
#             "use_color": True,
#             "use_lineart_2_style": "formal",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V13 — sketch improved",
#         "prompt": "How the human heart pumps blood through the circulatory system",
#         "opts": {
#             "use_color": True,
#             "use_lineart_2_style": "improved",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V14 — solo-male + voice instructions",
#         "prompt": "The history of basketball from peach baskets to the NBA",
#         "opts": {
#             "use_color": True,
#             "style": "solo-male",
#             "voice_instructions": "Deep authoritative voice like a sports commentator, energetic delivery",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V15 — video + voice instructions combo",
#         "prompt": "How the human immune system fights off viral infections",
#         "opts": {
#             "use_color": True,
#             "video_instructions": "Use warm tones and medical imagery, keep visuals clean and educational",
#             "voice_instructions": "Calm and reassuring tone, like a friendly doctor explaining to a patient",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V16 — leetcode + stylus + pencil cursor",
#         "prompt": "Solve this leetcode problem step by step, explain the approach and write the optimal solution",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "editorial",
#             "input_images": [LEETCODE_IMAGE],
#             "pen_style": "stylus",
#             "show_pencil_cursor": True,
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V17 — leetcode + marker pen",
#         "prompt": "Walk through this coding problem, explain the brute force and optimal approach",
#         "opts": {
#             "use_color": True,
#             "use_2_style": True,
#             "image_style": "editorial",
#             "input_images": [LEETCODE_IMAGE],
#             "pen_style": "marker",
#             "timing": "0.25",
#         },
#     },
#     {
#         "name": "V18 — user images + user videos",
#         "prompt": "Create an engaging explainer about SSH remote server connections using the provided materials",
#         "opts": {
#             "use_color": True,
#             "user_images": [LOGO_IMAGE],
#             "user_images_descriptions": ["Company logo for branding overlay"],
#             "user_videos": [SSH_VIDEO],
#             "user_videos_description": ["Screen recording of SSH terminal connection"],
#             "timing": "0.25",
#         },
#     },
# ]
VIDEO_TESTS = []


# ── Helpers ──────────────────────────────────────────────────────────────────────

def fmt_opts(opts: dict) -> str:
    lines = []
    for k, v in opts.items():
        val = repr(v) if isinstance(v, str) else str(v)
        if len(val) > 80:
            val = val[:77] + "..."
        lines.append(f"      {k}: {val}")
    return "\n".join(lines)


def print_final_results(results: list, wall_time: float) -> None:
    passed = [r for r in results if r["status"] == "passed"]
    failed = [r for r in results if r["status"] == "failed"]

    print(f"\n\n{'=' * 72}")
    print(" FINAL RESULTS — ALL OUTPUT URLs")
    print(f"{'=' * 72}\n")

    if not passed:
        print("  No completed jobs with URLs.\n")
    else:
        for i, r in enumerate(passed, 1):
            tag = "[PODCAST]" if r["type"] == "podcast" else "[VIDEO] "
            print(f"  {i:2d}. {tag} {r['name']}  ({r['elapsed']}s)")
            print(f"      URL: {r.get('url', 'N/A')}")
            if r.get("script"):
                print(f"      Script: {r['script'][:100]}...")
            print()

    if failed:
        print(f"{'─' * 72}")
        print(f"  FAILED JOBS ({len(failed)}):\n")
        for i, r in enumerate(failed, 1):
            print(f"  {i:2d}. {r['name']}  ({r['elapsed']}s)")
            print(f"      Error: {r.get('error', 'unknown')}")
        print()

    print(f"{'=' * 72}")
    print(
        f"  TOTAL: {len(results)} jobs  |  "
        f"PASSED: {len(passed)}  |  "
        f"FAILED: {len(failed)}  |  "
        f"WALL TIME: {wall_time:.0f}s"
    )
    print(f"{'=' * 72}")


# ── Main ─────────────────────────────────────────────────────────────────────────

def main():
    if not API_KEY:
        print("ERROR: Set API_KEY at the top of this file before running.")
        sys.exit(1)

    total = len(PODCAST_TESTS) + len(VIDEO_TESTS)
    print("=" * 72)
    print("  Golpo Python SDK — Test Suite")
    print(f"  {len(PODCAST_TESTS)} podcasts  |  {len(VIDEO_TESTS)} videos  |  {total} total")
    print("=" * 72)

    all_results = []
    wall_start = time.time()

    # ── Podcast tests ──
    if PODCAST_TESTS:
        print(f"\n  PODCAST TESTS ({len(PODCAST_TESTS)})\n")
        for i, tc in enumerate(PODCAST_TESTS):
            label = f"[{i + 1}/{len(PODCAST_TESTS)}] {tc['name']}"
            print(f"{'─' * 72}")
            print(f">>  {label}")
            print(f"    prompt: \"{tc['prompt']}\"")
            print(f"    opts:\n{fmt_opts(tc['opts'])}")
            print(f"    Waiting for completion...", flush=True)

            start = time.time()
            try:
                url, script = client.create_podcast(
                    tc["prompt"],
                    poll_interval=3,
                    **tc["opts"],
                )
                elapsed = round(time.time() - start, 1)
                print(f"  PASSED ({elapsed}s)")
                print(f"    url: {url}")
                if script:
                    print(f"    script: {script[:120]}...")
                all_results.append({
                    "name": tc["name"], "type": "podcast", "status": "passed",
                    "elapsed": elapsed, "url": url, "script": script,
                })
            except Exception as e:
                elapsed = round(time.time() - start, 1)
                print(f"  FAILED ({elapsed}s) — {e}")
                traceback.print_exc()
                all_results.append({
                    "name": tc["name"], "type": "podcast", "status": "failed",
                    "elapsed": elapsed, "error": str(e),
                })

    # ── Video tests ──
    if VIDEO_TESTS:
        print(f"\n  VIDEO TESTS ({len(VIDEO_TESTS)})\n")
        for i, tc in enumerate(VIDEO_TESTS):
            label = f"[{i + 1}/{len(VIDEO_TESTS)}] {tc['name']}"
            print(f"{'─' * 72}")
            print(f">>  {label}")
            print(f"    prompt: \"{tc['prompt']}\"")
            print(f"    opts:\n{fmt_opts(tc['opts'])}")
            print(f"    Waiting for completion...", flush=True)

            start = time.time()
            try:
                url, script = client.create_video(
                    tc["prompt"],
                    poll_interval=3,
                    **tc["opts"],
                )
                elapsed = round(time.time() - start, 1)
                print(f"  PASSED ({elapsed}s)")
                if url:
                    print(f"    url: {url}")
                if script:
                    print(f"    script: {script[:120]}...")
                all_results.append({
                    "name": tc["name"], "type": "video", "status": "passed",
                    "elapsed": elapsed, "url": url, "script": script,
                })
            except Exception as e:
                elapsed = round(time.time() - start, 1)
                print(f"  FAILED ({elapsed}s) — {e}")
                traceback.print_exc()
                all_results.append({
                    "name": tc["name"], "type": "video", "status": "failed",
                    "elapsed": elapsed, "error": str(e),
                })

    # ── Summary ──
    wall_time = round(time.time() - wall_start, 1)
    print_final_results(all_results, wall_time)

    fail_count = sum(1 for r in all_results if r["status"] == "failed")
    if fail_count > 0:
        sys.exit(1)


if __name__ == "__main__":
    main()
