#!/usr/bin/env python3
"""
Test runner for one_minute_history with updated prompt and fixed evaluator.
Uses the Bernays/tobacco premise that was already researched.
"""

import json
import sys
from pathlib import Path

# Add project root to path
sys.path.insert(0, str(Path(__file__).parent))

from video_generation import run_video_generation_chain

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


def main():
    # Load the pre-researched opportunity
    input_file = OUTPUT_DIR / "layer4_input_one_minute_history.json"

    if not input_file.exists():
        print(f"[ERROR] Input file not found: {input_file}")
        return 1

    with open(input_file) as f:
        opportunity = json.load(f)

    print("=" * 70)
    print("ONE MINUTE HISTORY TEST")
    print("=" * 70)
    print(f"Premise: {opportunity.get('premise', 'N/A')}")
    print(f"Research words: {len(opportunity.get('research_report_content', '').split())}")
    print("=" * 70)
    print()

    # Run the v4 pipeline
    result = run_video_generation_chain(
        opportunity=opportunity,
        channel_id="one_minute_history",
        prompt_version="v4",
        target_duration=90
    )

    # Output is now auto-saved to channel folder by the pipeline
    # Check what was created

    print()
    print("=" * 70)
    print("RESULTS")
    print("=" * 70)

    # Print key metrics
    if "layer4_evaluation" in result:
        eval_data = result["layer4_evaluation"]
        print(f"Verdict: {eval_data.get('verdict', 'N/A')}")
        print(f"Composite Score: {eval_data.get('composite_score', 'N/A')}")

        # Print gut check if present
        if "gut_check" in eval_data:
            gc = eval_data["gut_check"]
            print(f"\nGut Check:")
            print(f"  Would stop scrolling: {gc.get('would_stop_scrolling', 'N/A')}")
            print(f"  Would watch to end: {gc.get('would_watch_to_end', 'N/A')}")
            print(f"  Would send to someone: {gc.get('would_send_to_someone', 'N/A')}")
            if gc.get("discrepancy_with_score"):
                print(f"  DISCREPANCY: {gc.get('discrepancy_explanation', 'N/A')}")

        # Print domain averages
        if "domain_scores" in eval_data:
            print(f"\nDomain Scores:")
            for domain, data in eval_data["domain_scores"].items():
                if isinstance(data, dict) and "domain_average" in data:
                    print(f"  {domain}: {data['domain_average']:.2f}")

    if "script" in result:
        script = result["script"]
        meta = script.get("metadata", {})
        print(f"\nScript word count: {meta.get('word_count', 'N/A')}")

    # Show output location
    print(f"\nOutput auto-saved to: output/one_minute_history/")

    # List files in the channel folder
    channel_dir = OUTPUT_DIR / "one_minute_history"
    if channel_dir.exists():
        files = sorted(channel_dir.glob("*.json"), reverse=True)
        print(f"Channel folder contains {len(files)} video(s):")
        for f in files[:5]:  # Show latest 5
            print(f"  - {f.name}")

    return 0


if __name__ == "__main__":
    sys.exit(main())
