#!/opt/homebrew/bin/python3.11
"""
Integrate Rule 3 Markers (Scene/Music Boundaries)
Scans Audio Taxonomy and Visual Cuts to detect boundaries within Parent Chunks.
"""

import json
import psycopg2
import os

# Configuration
UUID = "384b0ff44aaaa1f1"
AUDIO_TAXONOMY_PATH = f"output/{UUID}/{UUID}.audio_taxonomy.json"
CUT_JSON_PATH = f"output/{UUID}/{UUID}.cut.json"
DB_URL = "postgresql://accusys@localhost:5432/momentry"


def load_json(path):
    if not os.path.exists(path):
        print(f"⚠️ File not found: {path}")
        return None
    with open(path, "r") as f:
        return json.load(f)


def main():
    print(f"🚀 Integrating Rule 3 Markers for {UUID}...")

    # 1. Load Data
    audio_data = load_json(AUDIO_TAXONOMY_PATH)
    cut_data = load_json(CUT_JSON_PATH)

    # Extract audio events list
    audio_events = audio_data.get("audio_taxonomy", []) if audio_data else []

    # Extract cut times
    cut_times = []
    if cut_data and "cuts" in cut_data:
        for cut in cut_data["cuts"]:
            cut_times.append(cut.get("start_time", 0))
    print(f"📂 Loaded {len(audio_events)} audio events and {len(cut_times)} cuts.")

    # 2. Connect to DB
    conn = psycopg2.connect(DB_URL)
    cur = conn.cursor()

    # Get all parent chunks
    cur.execute(
        "SELECT id, start_time, end_time FROM parent_chunks WHERE uuid = %s", (UUID,)
    )
    chunks = cur.fetchall()

    updated_count = 0

    for chunk_id, start, end in chunks:
        markers = []

        # A. Detect Music Boundaries
        # Look for transitions between Music and Non-Music in this window
        current_music_state = False

        # Check state before window (simplified: look at events before start)
        for ev in audio_events:
            if ev["timestamp"] >= start:
                break
            cats = ev.get("categories", {})
            if "Artificial/Music" in cats and cats["Artificial/Music"] > 0.5:
                current_music_state = True

        # Scan window
        for ev in audio_events:
            if ev["timestamp"] < start:
                continue
            if ev["timestamp"] > end:
                break

            cats = ev.get("categories", {})
            is_music = "Artificial/Music" in cats and cats["Artificial/Music"] > 0.5

            if is_music and not current_music_state:
                markers.append(
                    {
                        "type": "music_start",
                        "time": ev["timestamp"],
                        "confidence": cats["Artificial/Music"],
                    }
                )
                current_music_state = True
            elif not is_music and current_music_state:
                markers.append({"type": "music_end", "time": ev["timestamp"]})
                current_music_state = False

        # B. Detect High Cut Density (Visual Scene Change)
        # Count cuts in this window
        cuts_in_window = [t for t in cut_times if start <= t <= end]
        if len(cuts_in_window) > 5:  # Heuristic: > 5 cuts in a chunk indicates montage
            markers.append(
                {
                    "type": "montage_detected",
                    "time": start + (end - start) / 2,
                    "count": len(cuts_in_window),
                }
            )

        # Save to DB
        if markers:
            cur.execute(
                "UPDATE parent_chunks SET rule_3_markers = %s WHERE id = %s",
                (json.dumps(markers), chunk_id),
            )
            updated_count += 1

    conn.commit()
    print(f"✅ Updated {updated_count} chunks with Rule 3 markers.")
    cur.close()
    conn.close()


if __name__ == "__main__":
    main()
