#!/usr/bin/env python3
"""Check and count a synthetic monthly report fixture.

SYNTHETIC EXAMPLE. Reads one explicit JSON file, writes nothing, uses no
network, and prints computed JSON to standard output.

Usage: python3 check_monthly_report.py path/to/monthly-report.json

Exit codes: 0 computed, 2 invalid input or usage.
"""

import json
import re
import calendar
import sys
from datetime import date
from pathlib import Path

GRAIN = "application_id"
KNOWN_STATUSES = ("approved", "pending", "withdrawn")
RECORD_KEYS = {"application_id", "application_date", "status"}
MAX_BYTES = 1_000_000


class ValidationError(Exception):
    """The input cannot be counted without guessing."""


def _iso_date(value, where):
    if not isinstance(value, str) or not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}", value):
        raise ValidationError(f"{where}: expected an ISO date string, got {type(value).__name__}")
    try:
        return date.fromisoformat(value)
    except ValueError:
        raise ValidationError(f"{where}: not a valid ISO date: {value!r}") from None


def _period(value):
    if not isinstance(value, str) or len(value) != 7 or value[4] != "-":
        raise ValidationError("period: expected YYYY-MM")
    try:
        year, month = int(value[:4]), int(value[5:])
        date(year, month, 1)
        return year, month
    except ValueError:
        raise ValidationError("period: expected YYYY-MM") from None


def _record(raw, index):
    where = f"records[{index}]"
    if not isinstance(raw, dict):
        raise ValidationError(f"{where}: expected an object, got {type(raw).__name__}")
    extra = set(raw) - RECORD_KEYS
    if extra:
        raise ValidationError(f"{where}: unexpected fields {sorted(extra)}")
    app_id = raw.get("application_id")
    if not isinstance(app_id, str) or not app_id.strip() or app_id != app_id.strip():
        raise ValidationError(f"{where}.application_id: expected a non-empty string without padding")
    if "application_date" not in raw or raw["application_date"] is None:
        raise ValidationError(f"{where}.application_date: required, never inferred")
    applied = _iso_date(raw["application_date"], f"{where}.application_date")
    status = raw.get("status")  # absent or null stays unknown, never invented
    if status is not None and status not in KNOWN_STATUSES:
        raise ValidationError(f"{where}.status: expected null or one of {list(KNOWN_STATUSES)}, got {status!r}")
    return app_id, applied, status


def compute(data):
    """Return the computed report for a parsed fixture, or raise ValidationError."""
    if not isinstance(data, dict):
        raise ValidationError("top level: expected an object")
    if data.get("synthetic") is not True:
        raise ValidationError("synthetic: this checker accepts explicitly labeled synthetic fixtures only")
    year, month = _period(data.get("period"))
    snapshot = _iso_date(data.get("snapshot_date"), "snapshot_date")
    if snapshot < date(year, month, calendar.monthrange(year, month)[1]):
        raise ValidationError("snapshot_date: must cover the complete reporting month")
    rows = data.get("records")
    if not isinstance(rows, list):
        raise ValidationError("records: expected a list")

    unique = {}
    originals = {}
    for index, raw in enumerate(rows):
        app_id, applied, status = _record(raw, index)
        if applied > snapshot:
            raise ValidationError(f"records[{index}]: {app_id} dated after the snapshot date")
        if app_id in unique and originals[app_id] != raw:
            raise ValidationError(f"records[{index}]: conflicting duplicate for {app_id}; not merged")
        unique[app_id] = (applied, status)
        originals[app_id] = raw

    cohort = {k: v for k, v in unique.items() if (v[0].year, v[0].month) == (year, month)}
    counts = {name: 0 for name in KNOWN_STATUSES}
    counts["unknown"] = 0
    for _applied, status in cohort.values():
        counts[status or "unknown"] += 1

    return {
        "synthetic": True,
        "label": "SYNTHETIC EXAMPLE. Computed from fictional records.",
        "period": data["period"],
        "snapshot_date": data["snapshot_date"],
        "grain": GRAIN,
        "raw_rows": len(rows),
        "duplicate_rows": len(rows) - len(unique),
        "excluded_applications": len(unique) - len(cohort),
        "cohort_applications": len(cohort),
        "status_counts": counts,
        "completed": None,
        "notes": [
            "Completed is undefined for this report and is not computed.",
            "Missing status is counted as unknown, not guessed.",
        ],
    }


def main(argv):
    if len(argv) != 2:
        print("usage: check_monthly_report.py FILE.json", file=sys.stderr)
        return 2
    path = Path(argv[1])
    try:
        if path.suffix != ".json" or path.is_symlink() or not path.is_file():
            raise ValidationError("input must be an existing regular .json file")
        if path.stat().st_size > MAX_BYTES:
            raise ValidationError("input file is too large")
        data = json.loads(path.read_text(encoding="utf-8"))
        result = compute(data)
    except (ValidationError, OSError, UnicodeDecodeError, json.JSONDecodeError) as exc:
        print(f"invalid: {exc}", file=sys.stderr)
        return 2
    print(json.dumps(result, indent=2, sort_keys=True))
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
