#!/usr/bin/env python3
"""Reproduce the 2026 public-service developer offer coverage check.

The script reports aggregate counts and a checksum only. It does not print or
store offer text, employer names, locations, or contact information.
"""

import argparse
import csv
import datetime as dt
import hashlib
import json
import re
import unicodedata
from pathlib import Path


SOURCE_URL = (
    "https://static.data.gouv.fr/resources/"
    "les-offres-diffusees-sur-choisir-le-service-public/"
    "20261117-110356/offres-datagouv-20261115.csv"
)
SNAPSHOT_DATE = "2026-11-15"
PERIOD_START = dt.date(2026, 1, 1)
PERIOD_END = dt.date(2026, 11, 15)
TARGET_OCCUPATION = "Développeuse / Développeur"
REQUIRED_COLUMNS = {
    "Référence",
    "Métier",
    "Date de première publication",
    "Compétences attendues",
}


def normalize(value: str | None) -> str:
    """Normalize Unicode and whitespace for exact field matching only."""
    return " ".join(unicodedata.normalize("NFKC", value or "").split())


def parse_publication_date(value: str | None) -> dt.date | None:
    normalized = normalize(value)
    iso_match = re.match(r"^(\d{4})-(\d{2})-(\d{2})", normalized)
    if iso_match:
        return dt.date.fromisoformat("-".join(iso_match.groups()))
    french_match = re.match(r"^(\d{2})/(\d{2})/(\d{4})", normalized)
    if french_match:
        day, month, year = map(int, french_match.groups())
        return dt.date(year, month, day)
    return None


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        for chunk in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def analyze(path: Path) -> dict[str, object]:
    digest = sha256_file(path)
    total_rows = 0
    malformed_rows = 0
    occupation_rows = 0
    period_rows = 0
    missing_dates = 0
    unparseable_dates = 0
    outside_period_rows = 0
    duplicate_references = 0
    conflicting_duplicate_skills = 0
    unique_offers: dict[str, tuple[str, dt.date]] = {}
    period_dates: list[dt.date] = []

    with path.open("r", encoding="utf-8-sig", newline="") as source:
        reader = csv.DictReader(source, delimiter=";")
        columns = set(reader.fieldnames or [])
        missing_columns = sorted(REQUIRED_COLUMNS - columns)
        if missing_columns:
            raise ValueError(f"Missing expected CSV columns: {missing_columns}")

        for row in reader:
            if None in row or any(value is None for value in row.values()):
                malformed_rows += 1
                continue
            total_rows += 1
            if normalize(row.get("Métier")) != TARGET_OCCUPATION:
                continue
            occupation_rows += 1

            raw_date = normalize(row.get("Date de première publication"))
            if not raw_date:
                missing_dates += 1
                continue
            publication_date = parse_publication_date(raw_date)
            if publication_date is None:
                unparseable_dates += 1
                continue
            if not PERIOD_START <= publication_date <= PERIOD_END:
                outside_period_rows += 1
                continue

            period_rows += 1
            period_dates.append(publication_date)
            reference = normalize(row.get("Référence"))
            if not reference:
                raise ValueError("An in-period target offer has no reference")
            skill_text = normalize(row.get("Compétences attendues"))
            if reference in unique_offers:
                duplicate_references += 1
                if unique_offers[reference][0] != skill_text:
                    conflicting_duplicate_skills += 1
            else:
                # Keep text only in memory during this run to detect conflicts.
                unique_offers[reference] = (skill_text, publication_date)

    unique_count = len(unique_offers)
    offers_with_skills = sum(bool(text) for text, _ in unique_offers.values())
    coverage = offers_with_skills / unique_count if unique_count else 0

    return {
        "source": SOURCE_URL,
        "snapshotDate": SNAPSHOT_DATE,
        "periodStartInclusive": PERIOD_START.isoformat(),
        "periodEndInclusive": PERIOD_END.isoformat(),
        "sha256": digest,
        "wellFormedRowsInSnapshot": total_rows,
        "malformedRowsInSnapshot": malformed_rows,
        "occupation": TARGET_OCCUPATION,
        "occupationRowsInSnapshot": occupation_rows,
        "occupationRowsInPeriod": period_rows,
        "uniqueReferencesInPeriod": unique_count,
        "duplicateRowsInPeriod": duplicate_references,
        "conflictingDuplicateSkillFields": conflicting_duplicate_skills,
        "occupationRowsWithMissingPublicationDate": missing_dates,
        "occupationRowsWithUnparseablePublicationDate": unparseable_dates,
        "occupationRowsOutsidePeriod": outside_period_rows,
        "uniqueOffersWithCompetenciesField": offers_with_skills,
        "uniqueOffersWithoutCompetenciesField": unique_count - offers_with_skills,
        "competenciesFieldCoveragePercent": round(coverage * 100, 1),
        "firstPublicationMinInPeriod": min(period_dates).isoformat() if period_dates else None,
        "firstPublicationMaxInPeriod": max(period_dates).isoformat() if period_dates else None,
        "skillFrequenciesComputed": False,
    }


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Count offers and competency-field coverage, not skill frequencies."
    )
    parser.add_argument(
        "csv_file",
        type=Path,
        help="Local copy of the public data.gouv.fr CSV snapshot",
    )
    args = parser.parse_args()
    print(json.dumps(analyze(args.csv_file), ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
