"""Check the adjacent synthetic fixtures. Offline only; never connects to Tally or AI."""

import csv
import json
from decimal import Decimal
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def rows(name):
    with (ROOT / name).open(newline="", encoding="utf-8") as source:
        return list(csv.DictReader(source))


def decisions(events, mapping):
    accepted, seen, output = {}, {}, []
    for event in events:
        key = (event["company"], event["invoice"], event["revision"])
        document = key[:2]
        fingerprint = (event["item"], event["quantity"], event["unit_price"])
        if key in seen:
            output.append("skip_replay" if seen[key] == fingerprint else "hold_conflicting_replay")
        elif document in accepted:
            output.append("review_amendment")
        elif event["item"] not in mapping:
            output.append("hold_mapping")
        else:
            amount = Decimal(event["quantity"]) * Decimal(event["unit_price"])
            if amount <= 0:
                output.append("hold_invalid_amount")
                continue
            accepted[document] = amount
            seen[key] = fingerprint
            output.append("propose")
    return output, list(accepted.values())


def main():
    expected = json.loads((ROOT / "tally-expected-results.json").read_text())
    events = rows("tally-source-events.csv")
    actual, amounts = decisions(events, expected["mapping"])
    assert actual == expected["decisions"], (actual, expected["decisions"])
    assert len(amounts) == expected["proposed_vouchers"]
    assert sum(amounts) == expected["proposed_amount_excluding_tax"]
    # The same identifier with changed contents must not be silently skipped.
    assert decisions([events[0], dict(events[0], quantity="99")], expected["mapping"])[0][-1] == "hold_conflicting_replay"
    # Identical invoice numbers in different companies remain separate operations.
    assert len(decisions([events[0], dict(events[0], company="DEMO-OTHER")], expected["mapping"])[1]) == 2

    for row in rows("job-work-register.csv"):
        assert Decimal(row["sent"]) - Decimal(row["received"]) - Decimal(row["approved_loss"]) == Decimal(row["outstanding"])
        assert Decimal(row["quality_hold_within_received"]) <= Decimal(row["received"])
    assert Decimal("100") - Decimal("70") - Decimal("3") == Decimal("27")
    for row in rows("grn-exceptions.csv"):
        assert sum(Decimal(row[k]) for k in ["accepted", "quality_hold", "rejected"]) == Decimal(row["physically_received"])
        assert Decimal(row["ordered"]) - Decimal(row["physically_received"]) == Decimal(row["short_receipt"])

    reference = json.loads((ROOT / "reporting-answer-key.json").read_text())
    data = rows("reporting-input.csv")
    totals = {period: sum(Decimal(r["net_sales_inr"]) for r in data if r["period"] == period) for period in ["prior", "current"]}
    for period, value in totals.items():
        assert value == reference[period + "_net_sales_inr"]
    change = totals["current"] - totals["prior"]
    assert change == reference["change_inr"]
    assert change / totals["prior"] * 100 == reference["change_percent"]
    for channel in ["Direct", "Wholesale"]:
        by_period = {r["period"]: Decimal(r["net_sales_inr"]) for r in data if r["channel"] == channel}
        assert (by_period["current"] - by_period["prior"]) / by_period["prior"] * 100 == reference[channel.lower() + "_change_percent"]
    print("PASS: mapping simulation, replay/conflict/company cases, job-work/GRN quantities and reporting answer key.")
    print("Scope: synthetic offline checks; no Tally runtime, Claude generation or client outcome tested.")


if __name__ == "__main__":
    main()
