#!/usr/bin/env python3
"""Seed execution.db with EP999 test data for pressure testing.

Creates 6 shots in various states to exercise the Dailies priority queue:
  - EP999_SH01: failed (P1 — dead shots surface first)
  - EP999_SH02: video_ready (P2 — Gate 3 video drift review)
  - EP999_SH03: previs_generated (P3 — previs approval needed)
  - EP999_SH04: video_complete with 2 takes (P4 — take selection)
  - EP999_SH05: previs_pending (default — waiting for generation)
  - EP999_SH06: previs_pending (default — waiting for generation)

Usage:
    python tests/seed_test_db.py
    python tests/seed_test_db.py --clean   # wipe DB first
"""

import argparse
import sys
from pathlib import Path

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

from recoil.execution.execution_store import ExecutionStore


def seed(clean: bool = False):
    store = ExecutionStore()
    db_path = store.db_path

    if clean and db_path.exists():
        store.close()
        db_path.unlink()
        # Also remove WAL/SHM files
        for suffix in (".db-wal", ".db-shm"):
            p = db_path.with_suffix(suffix)
            if p.exists():
                p.unlink()
        print(f"  Cleaned {db_path}")
        store = ExecutionStore()

    shots = [
        {
            "shot_id": "EP999_SH01",
            "episode_id": "EP999",
            "pipeline": "still",
            "model": "gemini-3-pro-image-preview",
            "status": "failed",
            "error_message": "Gate 2 semantic check: subject mismatch — expected 'space station' got 'ocean platform'",
            "attempts": 2,
            "max_attempts": 3,
            "cost_incurred": 0.312,
            "session_id": "test-session-001",
            "gate_results": {
                "gate_1": {"passed": True, "score": 0.92},
                "gate_2": {"passed": False, "score": 0.31, "reason": "subject mismatch"},
            },
            "takes": [],
        },
        {
            "shot_id": "EP999_SH02",
            "episode_id": "EP999",
            "pipeline": "t2v",
            "model": "kling-v3",
            "status": "video_ready",
            "output_path": "output/frames/ep_999/EP999_SH02_take1.mp4",
            "attempts": 1,
            "max_attempts": 3,
            "cost_incurred": 0.673,
            "session_id": "test-session-001",
            "gate_results": {
                "gate_1": {"passed": True, "score": 0.95},
                "gate_2": {"passed": True, "score": 0.88},
                "gate_3": {"passed": True, "score": 0.76, "drift_frames": [12, 47]},
            },
            "takes": [
                {"take_id": "take_1", "path": "output/frames/ep_999/EP999_SH02_take1.mp4", "score": 0.76},
            ],
        },
        {
            "shot_id": "EP999_SH03",
            "episode_id": "EP999",
            "pipeline": "i2v",
            "model": "kling-v3",
            "status": "previs_generated",
            "output_path": "output/previs/ep_999/EP999_SH03_previs.png",
            "attempts": 1,
            "max_attempts": 3,
            "cost_incurred": 0.039,
            "session_id": "test-session-001",
            "gate_results": {},
            "takes": [],
        },
        {
            "shot_id": "EP999_SH04",
            "episode_id": "EP999",
            "pipeline": "multi_shot",
            "model": "seeddance-2.0",
            "status": "video_complete",
            "output_path": "output/frames/ep_999/EP999_SH04_take2.mp4",
            "attempts": 2,
            "max_attempts": 3,
            "cost_incurred": 0.456,
            "session_id": "test-session-001",
            "gate_results": {
                "gate_1": {"passed": True, "score": 0.94},
                "gate_2": {"passed": True, "score": 0.91},
                "gate_3": {"passed": True, "score": 0.85},
            },
            "takes": [
                {"take_id": "take_1", "path": "output/frames/ep_999/EP999_SH04_take1.mp4", "score": 0.72},
                {"take_id": "take_2", "path": "output/frames/ep_999/EP999_SH04_take2.mp4", "score": 0.85},
            ],
        },
        {
            "shot_id": "EP999_SH05",
            "episode_id": "EP999",
            "pipeline": "multi_shot",
            "model": "seeddance-2.0",
            "status": "previs_pending",
            "attempts": 0,
            "max_attempts": 3,
            "cost_incurred": 0.0,
            "session_id": "test-session-001",
            "gate_results": {},
            "takes": [],
        },
        {
            "shot_id": "EP999_SH06",
            "episode_id": "EP999",
            "pipeline": "multi_shot",
            "model": "seeddance-2.0",
            "status": "previs_pending",
            "attempts": 0,
            "max_attempts": 3,
            "cost_incurred": 0.0,
            "session_id": "test-session-001",
            "gate_results": {},
            "takes": [],
        },
    ]

    store.insert_shots_batch(shots)

    # Verify
    summary = store.summary("EP999")
    print(f"\n  Seeded {summary['total_shots']} EP999 shots into {db_path}")
    print(f"  Status breakdown: {summary['by_status']}")
    print(f"  Total cost: ${summary['total_cost']:.4f}")

    # Verify dailies queue
    items = []
    items.extend(store.get_shots_by_status("dead", "failed"))
    items.extend(store.get_shots_by_status("video_ready"))
    items.extend(store.get_shots_by_status("previs_generated", "keyframe_generated"))
    video_complete = store.get_shots_by_status("video_complete")
    items.extend([s for s in video_complete if len(s.get("takes", [])) > 1])

    print(f"  Dailies queue items: {len(items)}")
    for item in items:
        print(f"    {item['shot_id']}: {item['status']}")

    store.close()
    print("\n  Done.\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Seed EP999 test data")
    parser.add_argument("--clean", action="store_true", help="Wipe DB before seeding")
    args = parser.parse_args()
    seed(clean=args.clean)
