#!/usr/bin/env python3
"""
KELYVO Gold Standard Audio Pack (v1.0.0) — Integrity Verifier & Quick Loader.

Zero external dependencies (Python 3.8+ standard library only).
Run inside the unzipped delivery folder:
    python3 verify_and_load.py
"""

import csv
import hashlib
import json
import os
import sys

ROOT = os.path.dirname(os.path.abspath(__file__))


def sha256_file(path: str) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def verify_sha256_manifest() -> int:
    manifest = os.path.join(ROOT, "SHA256SUMS.txt")
    if not os.path.exists(manifest):
        raise FileNotFoundError("SHA256SUMS.txt not found")
    checked = 0
    with open(manifest, encoding="utf-8") as f:
        for raw in f:
            line = raw.strip()
            if not line or line.startswith("#"):
                continue
            expected, relpath = line.split(None, 1)
            relpath = relpath.lstrip("*").strip()
            full = os.path.join(ROOT, relpath)
            if not os.path.exists(full):
                raise FileNotFoundError(f"Missing file listed in manifest: {relpath}")
            actual = sha256_file(full)
            if actual != expected:
                raise ValueError(f"SHA-256 mismatch for {relpath}: expected {expected}, got {actual}")
            checked += 1
    return checked


def verify_dataset() -> dict:
    with open(os.path.join(ROOT, "kelyvo_audio_gold_standard_v1.json"), encoding="utf-8") as f:
        pack = json.load(f)

    tracks = pack["tracks"]
    assert pack["dataset_metadata"]["schema"] == "kelyvo-audio-gold-v1"
    assert pack["dataset_metadata"]["track_count"] == len(tracks)

    # Verify JSONL parity
    with open(os.path.join(ROOT, "kelyvo_audio_gold_standard_v1.jsonl"), encoding="utf-8") as f:
        jsonl_rows = [json.loads(line) for line in f if line.strip()]
    assert len(jsonl_rows) == len(tracks), "JSONL row count mismatch"

    # Verify CSV parity
    with open(os.path.join(ROOT, "kelyvo_audio_gold_standard_v1_tracks.csv"), encoding="utf-8") as f:
        csv_tracks = list(csv.DictReader(f))
    with open(os.path.join(ROOT, "kelyvo_audio_gold_standard_v1_sections.csv"), encoding="utf-8") as f:
        csv_sections = list(csv.DictReader(f))
    assert len(csv_tracks) == len(tracks), "Tracks CSV row count mismatch"

    total_sections = 0
    for t in tracks:
        audio_full = os.path.join(ROOT, t["audio_file"])
        assert os.path.exists(audio_full), f"Missing audio asset: {t['audio_file']}"
        assert sha256_file(audio_full) == t["audio_sha256"], f"Audio SHA-256 mismatch: {t['sample_id']}"

        # Verify contiguous non-overlapping temporal boundaries
        secs = t["temporal_sections"]
        assert secs[0]["start_sec"] == 0.0, f"{t['sample_id']} does not start at 0.0s"
        assert abs(secs[-1]["end_sec"] - t["duration_sec"]) < 0.01, f"{t['sample_id']} end_sec mismatch"
        for i, s in enumerate(secs):
            assert s["end_sec"] > s["start_sec"], f"Invalid duration in {t['sample_id']} sec {i+1}"
            if i > 0:
                assert s["start_sec"] == secs[i - 1]["end_sec"], f"Non-contiguous boundary in {t['sample_id']} sec {i+1}"
        total_sections += len(secs)

        # Verify 1-5 Mix QA bounds
        mx = t["mix_qa_scorecard"]
        axes = [
            mx["mix_clarity"],
            mx["frequency_balance"],
            mx["vocal_intelligibility"],
            mx["dynamic_range"],
            mx["overall_production_quality"],
        ]
        assert all(1 <= v <= 5 for v in axes), f"Mix score out of bounds on {t['sample_id']}"
        assert abs(sum(axes) / 5.0 - mx["composite_mean"]) < 1e-6, f"Composite mean mismatch on {t['sample_id']}"

    assert len(csv_sections) == total_sections, "Sections CSV row count mismatch"
    assert pack["dataset_metadata"]["total_temporal_sections"] == total_sections
    return pack


def main() -> int:
    print("KELYVO Audio & Music Intelligence — Delivery Pack Verification")
    print("-" * 78)
    checked = verify_sha256_manifest()
    print(f"[PASS] SHA-256 Manifest verified ({checked} files bit-exact)")

    pack = verify_dataset()
    print(f"[PASS] Schema, JSONL, CSV parity & contiguous temporal boundaries verified")
    print("-" * 78)
    print(f"{'ID':<12} {'Title':<30} {'Musical Facts':<20} {'Sec':>3} {'Mix QA':>7} {'RMS dBFS':>9}")
    print("-" * 78)
    for t in pack["tracks"]:
        mm = t["musical_metadata"]
        mx = t["mix_qa_scorecard"]
        sp = t["audio_technical_specs"]
        facts = f"{mm['bpm']} BPM {mm['key']} {mm['mode']}"
        print(
            f"{t['sample_id']:<12} {t['title'][:29]:<30} {facts:<20} "
            f"{len(t['temporal_sections']):>3} {mx['composite_mean']:>5.1f}/5 {sp['rms_dbfs']:>8.2f}"
        )
    print("-" * 78)
    print("Ready for ML ingestion. Contact: hello@kelyvo.life | https://kelyvo.life/samples")
    return 0


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