from __future__ import annotations

import csv
from pathlib import Path

REQUIRED = {"artifact_id", "artifact_type", "title", "owner", "revision", "status", "source", "configuration"}
VALID_STATUS = {"draft", "in_review", "released", "superseded"}


def load_rows(path: Path) -> list[dict[str, str]]:
    with path.open(newline="", encoding="utf-8") as handle:
        return list(csv.DictReader(handle))


def validate(rows: list[dict[str, str]]) -> list[str]:
    problems: list[str] = []
    seen: set[str] = set()
    for index, row in enumerate(rows, start=2):
        missing = [field for field in REQUIRED if not row.get(field, "").strip()]
        if missing:
            problems.append(f"row {index}: missing {', '.join(sorted(missing))}")
        artifact_id = row.get("artifact_id", "").strip()
        if artifact_id in seen:
            problems.append(f"row {index}: duplicate artifact_id {artifact_id}")
        seen.add(artifact_id)
        if row.get("status") not in VALID_STATUS:
            problems.append(f"row {index}: invalid status {row.get('status')}")
    return problems


def released_by_configuration(rows: list[dict[str, str]], configuration: str) -> list[str]:
    return sorted(
        row["artifact_id"]
        for row in rows
        if row["configuration"] == configuration and row["status"] == "released"
    )


def main() -> None:
    rows = load_rows(Path("data/artifact_register.csv"))
    problems = validate(rows)
    released = released_by_configuration(rows, "B0")
    print("validation_problems =", problems)
    print("released_B0 =", released)
    assert problems == []
    assert released == ["BRK-CAD-001", "BRK-REQ-001", "BRK-TEST-001"]


if __name__ == "__main__":
    main()
