#!/usr/bin/env python3
"""Load and validate the sanitized EGXO release 1.0.0 public catalog."""

from __future__ import annotations

import argparse
import csv
import io
import json
from pathlib import Path
from urllib.request import urlopen


DEFAULT_CATALOG = (
    "https://egxodata.com/datasets/"
    "egxo-household-egocentric-video-evaluation-catalog.csv"
)
REQUIRED_COLUMNS = [
    "asset_id",
    "task_name",
    "duration_seconds",
    "width",
    "height",
    "fps",
]


def read_text(source: str) -> str:
    if source.startswith(("https://", "http://")):
        with urlopen(source, timeout=30) as response:
            return response.read().decode("utf-8")
    return Path(source).read_text(encoding="utf-8")


def load_catalog(source: str) -> list[dict[str, str | int]]:
    reader = csv.DictReader(io.StringIO(read_text(source)))
    if reader.fieldnames != REQUIRED_COLUMNS:
        raise ValueError(f"Unexpected columns: {reader.fieldnames!r}")

    records: list[dict[str, str | int]] = []
    seen: set[str] = set()
    for row in reader:
        asset_id = row["asset_id"]
        if asset_id in seen:
            raise ValueError(f"Duplicate asset_id: {asset_id}")
        seen.add(asset_id)
        records.append(
            {
                "asset_id": asset_id,
                "task_name": row["task_name"],
                "duration_seconds": int(row["duration_seconds"]),
                "width": int(row["width"]),
                "height": int(row["height"]),
                "fps": int(row["fps"]),
            }
        )
    return records


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("source", nargs="?", default=DEFAULT_CATALOG)
    args = parser.parse_args()
    records = load_catalog(args.source)
    print(
        json.dumps(
            {
                "records": len(records),
                "unique_asset_ids": len({record["asset_id"] for record in records}),
                "duration_seconds": sum(
                    int(record["duration_seconds"]) for record in records
                ),
                "first_record": records[0] if records else None,
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()
