#!/usr/bin/env python3
"""
Run Layer 4 pipeline for a single opportunity.
Usage: python run_single_opportunity.py <channel_id> <index>
"""

import json
import sys
from pathlib import Path
from datetime import datetime, timezone

sys.path.insert(0, str(Path(__file__).parent))

from video_generation import run_layer4_v4_pipeline

OUTPUT_DIR = Path(__file__).parent / "output"


def load_opportunity(channel_id: str, index: int) -> dict:
    """Load opportunity from analysis file."""
    opp_file = OUTPUT_DIR / f"analysis_opportunities_{channel_id}.json"

    if not opp_file.exists():
        raise FileNotFoundError(f"Analysis file not found: {opp_file}")

    with open(opp_file, "r") as f:
        data = json.load(f)

    opportunities = data.get("opportunities", [])

    if index < 0 or index >= len(opportunities):
        raise IndexError(f"Index {index} out of range (0-{len(opportunities)-1})")

    return opportunities[index]


def main():
    if len(sys.argv) < 3:
        print("Usage: python run_single_opportunity.py <channel_id> <index>")
        print("Example: python run_single_opportunity.py sixty_second_rabbit_hole 0")
        sys.exit(1)

    channel_id = sys.argv[1]
    index = int(sys.argv[2])

    print("=" * 70)
    print(f"RUNNING LAYER 4 PIPELINE")
    print(f"Channel: {channel_id}")
    print(f"Index: {index}")
    print("=" * 70)

    # Load opportunity
    print(f"\n[1] Loading opportunity...")
    opportunity = load_opportunity(channel_id, index)

    premise = opportunity.get("premise", "Unknown")
    weighted_score = opportunity.get("weighted_score", 0)
    research_words = opportunity.get("research_word_count", 0)

    print(f"    Premise: {premise}")
    print(f"    Score: {weighted_score}")
    print(f"    Research: {research_words} words")

    # Check research
    if not opportunity.get("research_report_content"):
        print("\n    WARNING: No research content found!")
        print("    The script will still run but quality may be lower.")

    # Run pipeline
    print(f"\n[2] Running Layer 4 pipeline...")
    print("-" * 70)

    result = run_layer4_v4_pipeline(
        opportunity=opportunity,
        channel_id=channel_id,
        target_duration=90,
        max_iterations=2
    )

    print("-" * 70)

    # Results
    print(f"\n[3] Results:")
    evaluation = result.get("evaluation", {})
    verdict = evaluation.get("verdict", "UNKNOWN")
    score = evaluation.get("composite_score", 0)
    iterations = result.get("iteration_count", 0)
    production_ready = result.get("production_ready", False)

    print(f"    Verdict: {verdict}")
    print(f"    Score: {score:.2f}")
    print(f"    Iterations: {iterations}")
    print(f"    Production Ready: {production_ready}")

    # Check output
    channel_dir = OUTPUT_DIR / channel_id
    if channel_dir.exists():
        outputs = list(channel_dir.glob("*.json"))
        if outputs:
            latest = max(outputs, key=lambda p: p.stat().st_mtime)
            print(f"\n    Output saved: {latest}")

    print("\n" + "=" * 70)
    print("COMPLETE")
    print("=" * 70)


if __name__ == "__main__":
    main()
