#!/usr/bin/env python3
"""
Phase 4: Deck Generator — Orchestrates output format selection.
Supports: gamma | gslides | reveal | all
"""

import argparse
import json
import os
import sys
import subprocess
from pathlib import Path

WORKSPACE = Path.home() / ".openclaw" / "workspace"
SKILL_DIR = Path(__file__).parent.parent


def load_config() -> dict:
    config_path = Path.home() / ".baoyu-skills" / "baoyu-slides" / "config.json"
    if config_path.exists():
        return json.loads(config_path.read_text())
    return {}


def run_script(script: str, args_list: list[str]) -> int:
    script_path = SKILL_DIR / "scripts" / script
    result = subprocess.run(
        [sys.executable, str(script_path)] + args_list,
        capture_output=False  # show output directly
    )
    return result.returncode


def generate(outline_path: str, fmt: str, title: str = None, output_dir: str = None) -> dict:
    config = load_config()
    results = {}

    if not output_dir:
        slug = Path(outline_path).stem.replace('02-slide-outline', '').strip('-')
        output_dir = str(WORKSPACE / "presentations" / slug)

    os.makedirs(output_dir, exist_ok=True)

    if fmt in ('gamma', 'all'):
        print("\n🎨 Generating Gamma presentation...")
        gamma_api_key = (
            config.get('gamma_api_key') or
            os.environ.get('GAMMA_API_KEY', '')
        )
        args = ["--outline", outline_path]
        if gamma_api_key:
            args += ["--api-key", gamma_api_key]
        else:
            args += ["--markdown-only"]
            print("  [No Gamma API key — will output markdown for manual import]")

        rc = run_script("gamma_api.py", args)
        results['gamma'] = {'status': 'ok' if rc == 0 else 'error'}

    if fmt in ('gslides', 'all'):
        print("\n📊 Generating Google Slides deck...")
        args = ["--outline", outline_path]
        if title:
            args += ["--title", title]
        rc = run_script("gslides.py", args)
        results['gslides'] = {'status': 'ok' if rc == 0 else 'error'}

    if fmt in ('reveal', 'all'):
        print("\n🌐 Generating Reveal.js presentation...")
        reveal_dir = os.path.join(output_dir, "reveal")
        rc = run_script("reveal.py", [
            "--outline", outline_path,
            "--out-dir", reveal_dir
        ])
        if rc == 0:
            results['reveal'] = {
                'status': 'ok',
                'path': os.path.join(reveal_dir, 'index.html')
            }
        else:
            results['reveal'] = {'status': 'error'}

    return results


def main():
    parser = argparse.ArgumentParser(description="Generate slide deck from outline")
    parser.add_argument("--outline", required=True, help="Path to slide-outline.yaml")
    parser.add_argument("--format", default="gslides",
                        choices=["gamma", "gslides", "reveal", "all"],
                        help="Output format")
    parser.add_argument("--title", help="Override deck title")
    parser.add_argument("--out-dir", help="Output directory")
    args = parser.parse_args()

    print(f"\n🚀 baoyu-slides: Generating {args.format} deck")
    print(f"   Outline: {args.outline}")

    results = generate(
        outline_path=args.outline,
        fmt=args.format,
        title=args.title,
        output_dir=args.out_dir,
    )

    print("\n📋 Generation Summary:")
    for fmt, r in results.items():
        status = "✅" if r['status'] == 'ok' else "❌"
        path = r.get('path', r.get('url', ''))
        print(f"  {status} {fmt}: {path or r['status']}")


if __name__ == "__main__":
    main()
