#!/usr/bin/env python3
"""Validate and score the Chapter 3 open-source tool evaluation matrix."""

from __future__ import annotations

import csv
from pathlib import Path

LAB_DIR = Path(__file__).resolve().parents[1]
MATRIX_PATH = LAB_DIR / "tool_evaluation_matrix.csv"
REQUIRED_CRITERIA = {
    "functional_fit",
    "operational_maturity",
    "community_health",
    "security_compliance",
    "integration_ecosystem",
    "learning_curve",
    "cost_scalability",
}
NON_CANDIDATE_COLUMNS = {"criterion", "weight", "evidence_required"}


def read_rows() -> list[dict[str, str]]:
    if not MATRIX_PATH.exists():
        raise SystemExit(f"Missing matrix: {MATRIX_PATH}")
    with MATRIX_PATH.open(newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def main() -> None:
    rows = read_rows()
    if not rows:
        raise SystemExit("The evaluation matrix is empty.")

    criteria = {row["criterion"] for row in rows}
    missing = REQUIRED_CRITERIA - criteria
    if missing:
        raise SystemExit(f"Missing required criteria: {', '.join(sorted(missing))}")

    candidates = [c for c in rows[0] if c not in NON_CANDIDATE_COLUMNS]
    if not candidates:
        raise SystemExit("No candidate tool columns found.")

    total_weight = sum(float(row["weight"]) for row in rows)
    if abs(total_weight - 1.0) > 0.0001:
        raise SystemExit(f"Weights must sum to 1.0; found {total_weight:.4f}")

    print("Weighted scores")
    print("---------------")
    for candidate in candidates:
        score = sum(float(row["weight"]) * float(row[candidate]) for row in rows)
        print(f"{candidate}: {score:.2f}")

    print("\nValidation passed: matrix shape, criteria, and weights are valid.")


if __name__ == "__main__":
    main()
