#!/usr/bin/env python3
"""v0.4: footage_key canônico — contrato name=f\"{cam}_{fileStem}\" (sem [:-4])."""
import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import vlib as V


class TestFootageKey(unittest.TestCase):
    def test_contract_with_cam(self):
        """Com cam: strip exato — independente de pasta/hífen/maiúsculas."""
        cases = [
            ("cam1_marcelo_C8196", "cam1_marcelo", "C8196"),
            ("cam2_rafa_C0056.MP4", "cam2_rafa", "C0056"),
            ("cam1_carao1fabr_PRE_0172cerimonia", "cam1_carao1fabr", "PRE_0172cerimonia"),
            ("cam2_william_C5333cerimoniacam2", "cam2_william", "C5333cerimoniacam2"),
            ("cam2_joao-silva_clipA", "cam2_joao-silva", "clipA"),
            ("cam1_MyCam_Wedding_Take_01", "cam1_MyCam", "Wedding_Take_01"),
            ("cam10_camx_C99", "cam10_camx", "C99"),
            ("cam1_salao_IMG_0001", "cam1_salao", "IMG_0001"),
            ("cam1_foo_bar_baz", "cam1_foo", "bar_baz"),
        ]
        for name, cam, want in cases:
            self.assertEqual(
                V.footage_key(name, cam=cam), want,
                msg=f"name={name!r} cam={cam!r}",
            )

    def test_no_collapse_digits(self):
        """Regressão Nathália: [:-4] virava marcelo_C e colapsava N clips."""
        k = V.footage_key("cam1_marcelo_C8196", cam="cam1_marcelo")
        self.assertEqual(k, "C8196")
        self.assertNotEqual(k, "marcelo_C")
        # 31 clips → 31 keys distintas
        keys = {
            V.footage_key(f"cam1_marcelo_C{n}", cam="cam1_marcelo")
            for n in range(8196, 8227)
        }
        self.assertEqual(len(keys), 31)

    def test_heuristic_without_cam(self):
        self.assertEqual(V.footage_key("cam1_marcelo_C8196"), "C8196")
        self.assertEqual(V.footage_key("cam1_carao1fabr_PRE_0172cerimonia"), "PRE_0172cerimonia")
        self.assertEqual(V.footage_key("cam1_PRE_0172cerimonia.wav"), "PRE_0172cerimonia")

    def test_resolve_media_path(self):
        M = {
            "C8196": "/a/C8196.MP4",
            "PRE_0172cerimonia": "/b/x.MP4",
            "Wedding_Take_01": "/c/w.MP4",
            "clipA": "/d/a.mov",
        }
        self.assertEqual(
            V.resolve_media_path("cam1_marcelo_C8196", M, cam="cam1_marcelo"),
            "/a/C8196.MP4",
        )
        self.assertEqual(
            V.resolve_media_path("cam1_carao1fabr_PRE_0172cerimonia", M, cam="cam1_carao1fabr"),
            "/b/x.MP4",
        )
        self.assertEqual(
            V.resolve_media_path("cam1_MyCam_Wedding_Take_01", M, cam="cam1_MyCam"),
            "/c/w.MP4",
        )
        self.assertEqual(
            V.resolve_media_path("cam2_joao-silva_clipA", M, cam="cam2_joao-silva"),
            "/d/a.mov",
        )

    def test_real_weddings_if_present(self):
        """Paula + Nathália: todo clip resolve em media_paths do workdir (se existir)."""
        import json
        from pathlib import Path
        home = Path.home()
        for slug in ("casamento-nathalia-e-gleydson", "casamento-paula-e-ronaldo"):
            base = home / "Library/Caches/VideoTask/pipeline" / slug
            mp_p = base / "media_paths.json"
            wed = base / "weddings" / slug / "placements.json"
            if not mp_p.exists() or not wed.exists():
                continue
            mp = json.loads(mp_p.read_text())
            clips = json.loads(wed.read_text()).get("clips") or []
            for c in clips:
                k = V.footage_key(c["name"], cam=c.get("cam"))
                p = V.resolve_media_path(c["name"], mp, cam=c.get("cam"))
                self.assertTrue(k, msg=c["name"])
                self.assertIsNotNone(p, msg=f"{slug} miss {c['name']} key={k}")
                # paridade com Swift basename = name.dropFirst(cam+_)
                cam = c["cam"]
                if c["name"].startswith(cam + "_"):
                    self.assertEqual(k, c["name"][len(cam) + 1 :])


if __name__ == "__main__":
    unittest.main(verbosity=2)
