"""Validate a classification CSV and count its categories. Standard library only.
Usage: python3 count-ticket-categories.py classifications.csv
Required columns: ticket_id,category. Evidence columns may be included.
This validates structure and completeness for the 12-ticket sample, not correctness.
"""
import csv
import sys
from collections import Counter

EXPECTED_IDS = {f"T{i:03d}" for i in range(1, 13)}
ALLOWED = {"billing", "access", "delivery", "feature", "bug", "unknown"}

def count_categories(filename):
    with open(filename, newline="", encoding="utf-8-sig") as handle:
        reader = csv.DictReader(handle)
        if not {"ticket_id", "category"}.issubset(reader.fieldnames or []):
            raise ValueError("CSV must contain ticket_id and category columns")
        seen = set()
        counts = Counter()
        for row in reader:
            ticket_id = (row.get("ticket_id") or "").strip()
            category = (row.get("category") or "").strip().lower()
            if ticket_id not in EXPECTED_IDS or ticket_id in seen:
                raise ValueError(f"Unexpected or duplicate ticket ID: {ticket_id}")
            if category not in ALLOWED:
                raise ValueError(f"Unsupported category for {ticket_id}: {category}")
            seen.add(ticket_id)
            counts[category] += 1
        missing = EXPECTED_IDS - seen
        if missing:
            raise ValueError(f"Missing ticket IDs: {', '.join(sorted(missing))}")
        return counts

if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python3 count-ticket-categories.py classifications.csv")
    try:
        result = count_categories(sys.argv[1])
    except (ValueError, OSError) as error:
        raise SystemExit(str(error))
    for category in sorted(ALLOWED):
        print(f"{category}: {result[category]}")
    print(f"total: {sum(result.values())}")
