#!/opt/homebrew/bin/python3.11
"""
Store Scene to Qdrant v1.11 — Upsert E4B-enriched scenes to momentry_scenes collection

Reads: {file_uuid}.e4b_per_cut.json
Output: Upsert to Qdrant collection "momentry_scenes"

Each point:
  vector: f32[768] from corrected_text + summary
  payload: file_uuid, chunk_id, text_content, summary_text, scene_type,
           scene_description, key_objects, speakers, face_traces,
           time_range, child_chunk_ids
"""

import json, os, sys, argparse, time
import requests


EMBEDDING_URL = os.environ.get("EMBEDDING_URL", "http://localhost:11436/v1/embeddings")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
COLLECTION = "momentry_scenes"
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev")


def get_embedding(text: str) -> list:
    resp = requests.post(EMBEDDING_URL, json={"input": [text[:512]]}, timeout=30)
    if resp.status_code == 200:
        data = resp.json()
        if data.get("data"):
            return data["data"][0]["embedding"]
    raise RuntimeError(f"Embedding failed: {resp.status_code} {resp.text[:200]}")


def main():
    parser = argparse.ArgumentParser(description="Store scenes to Qdrant v1.11")
    parser.add_argument("--file-uuid", required=True)
    parser.add_argument("--e4b-json", help="Path to e4b_per_cut.json")
    args = parser.parse_args()

    e4b_path = args.e4b_json or os.path.join(OUTPUT_DIR, f"{args.file_uuid}.e4b_per_cut.json")
    if not os.path.exists(e4b_path):
        print(f"❌ Not found: {e4b_path}")
        sys.exit(1)

    with open(e4b_path) as f:
        e4b_data = json.load(f)

    scenes = e4b_data.get("scenes", [])
    if not scenes:
        print("❌ No scenes in E4B data")
        sys.exit(1)

    print(f"📤 Upserting {len(scenes)} scenes → Qdrant {COLLECTION}")
    t0 = time.time()

    points = []
    for i, scene in enumerate(scenes):
        text = scene.get("corrected_text", "") or scene.get("original_asr", "")
        summary = scene.get("summary", "")
        embed_text = (summary or text)[:512]

        emb = get_embedding(embed_text)

        point_id = f"{args.file_uuid}_{scene['start_time']:.0f}_{scene['end_time']:.0f}"
        points.append({
            "id": point_id,
            "vector": emb,
            "payload": {
                "file_uuid": args.file_uuid,
                "chunk_id": f"scene_{i}",
                "text_content": text[:2000],
                "summary_text": summary[:1000],
                "scene_type": scene.get("scene_type", ""),
                "scene_description": (scene.get("scene_description", "") or "")[:500],
                "key_objects": scene.get("key_objects", []),
                "face_traces": scene.get("face_qa", []),
                "time_range": [scene["start_time"], scene["end_time"]],
            }
        })

    if points:
        resp = requests.put(
            f"{QDRANT_URL}/collections/{COLLECTION}/points",
            json={"points": points},
            timeout=120,
        )
        if resp.status_code == 200:
            elapsed = time.time() - t0
            print(f"✅ {len(points)} scenes upserted in {elapsed:.0f}s")
        else:
            print(f"⚠️ Qdrant error: {resp.status_code} {resp.text[:300]}")

    print("Done")


if __name__ == "__main__":
    main()
