"""Offline exception-ageing reporting prototype."""

import csv
import json
import sys
from pathlib import Path


PROFILE = "exception-ageing"
DEFAULT_ACTION = "assign an owner and resolve the oldest blocking exception"
PRIORITY_RANK = {"high": 0, "medium": 1, "normal": 2}


def as_number(value):
    """Convert a dataset numeric value to a float."""
    try:
        return float(value)
    except (TypeError, ValueError):
        return 0.0


def priority_for(row):
    """Apply the signed operational-priority policy to one source row."""
    delay_days = as_number(row.get("borrower_delay_days"))
    processor_minutes = as_number(row.get("processor_minutes"))
    send_back_count = as_number(row.get("send_back_count"))

    if (
        row.get("broker_escalation") == "1"
        or row.get("queue_assignment") == "missing"
        or delay_days >= 2
    ):
        return "high"
    if send_back_count >= 2 or processor_minutes >= 45:
        return "medium"
    return "normal"


def reason_for(row):
    """Use narrative reason text where supplied, falling back to the reason code."""
    return row.get("reason_text") or row.get("reason_code", "")


def finding_for(row):
    """Create the public, traceable finding representation for a source row."""
    return {
        "case_id": row.get("case_id", ""),
        "priority": priority_for(row),
        "category": row.get("queue_assignment", ""),
        "current_owner": row.get("current_owner", ""),
        "reason": reason_for(row),
        "action": DEFAULT_ACTION,
        "borrower_delay_days": as_number(row.get("borrower_delay_days")),
        "processor_minutes": as_number(row.get("processor_minutes")),
    }


def analyze_rows(rows):
    """Return a deterministic exception-ageing report for CSV dictionary rows."""
    source_rows = list(rows)
    in_scope = [
        row for row in source_rows
        if as_number(row.get("borrower_delay_days")) >= 1
    ]
    findings = [finding_for(row) for row in in_scope]
    findings.sort(
        key=lambda finding: (
            PRIORITY_RANK[finding["priority"]],
            -finding["borrower_delay_days"],
            -finding["processor_minutes"],
            finding["case_id"],
        )
    )

    flagged_count = len(findings)
    source_count = len(source_rows)
    metrics = {
        "target_rate": (100 * flagged_count / source_count) if source_count else 0.0,
        "first_time_right_rate": (
            100 * sum(row.get("first_time_right") == "1" for row in in_scope) / flagged_count
            if flagged_count else 0.0
        ),
        "total_processor_minutes": sum(finding["processor_minutes"] for finding in findings),
        "total_delay_days": sum(finding["borrower_delay_days"] for finding in findings),
        "high_priority_count": sum(finding["priority"] == "high" for finding in findings),
    }
    return {
        "schema_version": "fde-prototype-output/1",
        "profile": PROFILE,
        "source_rows": source_count,
        "flagged_count": flagged_count,
        "findings": findings,
        "metrics": metrics,
    }


def main(argv=None):
    """Read a CSV input path and write one JSON document to the requested path."""
    arguments = sys.argv[1:] if argv is None else argv
    if len(arguments) != 2:
        raise SystemExit("usage: python solution.py INPUT_CSV OUTPUT_JSON")

    input_path = Path(arguments[0])
    output_path = Path(arguments[1])
    with input_path.open(newline="", encoding="utf-8") as handle:
        result = analyze_rows(csv.DictReader(handle))

    output_path.parent.mkdir(parents=True, exist_ok=True)
    with output_path.open("w", encoding="utf-8") as handle:
        json.dump(result, handle, indent=2, sort_keys=True)
        handle.write("\n")


if __name__ == "__main__":
    main()