#!/usr/bin/env python3
"""Independent Decimal reference for DN's fictional three-fill worksheet.

Reads the downloaded example JSON, a scenario export, or a bare inputs object.
No API, credentials, third-party packages or network calls are used.
"""
import argparse
from decimal import Decimal
import json
from pathlib import Path
import re

DECIMAL = re.compile(r"-?\d+(?:\.\d{1,4})?\Z")
INTEGER = re.compile(r"\d+\Z")
MAX_VALUE = Decimal("1000000000")
LABELS = {
    "q": "gross quantity",
    "d": "absolute net delta",
    "v": "absolute net vega",
}


def number(data, key, positive=False):
    raw = str(data[key]).strip()
    if not DECIMAL.fullmatch(raw) or len(raw) > 25:
        raise ValueError(f"{key}: use a plain decimal with at most four places")
    value = Decimal(raw)
    if abs(value) > MAX_VALUE or (positive and value <= 0):
        raise ValueError(f"{key}: outside the permitted numeric range")
    return value


def integer(data, key, minimum, maximum):
    raw = str(data[key]).strip()
    if not INTEGER.fullmatch(raw):
        raise ValueError(f"{key}: use unsigned whole milliseconds")
    value = int(raw)
    if not minimum <= value <= maximum:
        raise ValueError(f"{key}: outside the permitted integer range")
    return value


def text(value):
    result = format(value, "f")
    if "." in result:
        result = result.rstrip("0").rstrip(".")
    return "0" if Decimal(result) == 0 else result


def calculate(data):
    if data["scope"] != "same-fictional-instrument-group":
        return {"status": "unverified", "reason": "A single fictional option and protection group are not established."}
    mode = data["windowMode"]
    boundary = data["boundary"]
    metrics = data["metrics"]
    if mode not in ("first-fill-anchored", "trailing-comparison"):
        raise ValueError("Unsupported window mode")
    if boundary not in ("unknown", "at-or-above", "strictly-above"):
        raise ValueError("Unsupported threshold boundary")
    if metrics not in ("quantity-delta-vega", "quantity-only"):
        raise ValueError("Unsupported counter selection")
    window = integer(data, "windowMs", 1, 3600000)
    freeze = integer(data, "frozenMs", 0, 3600000)
    limits = {key: number(data, name, True) for key, name in
              (("q", "quantityLimit"), ("d", "deltaLimit"), ("v", "vegaLimit"))}
    opening = number(data, "initialPosition")
    current_delta = number(data, "currentDelta")
    current_vega = number(data, "currentVega")
    if abs(current_delta) > 1 or current_vega < 0:
        raise ValueError("Current delta must be within [-1,1]; current long-option vega must be nonnegative")
    fills = []
    for name in "ABC":
        fill = {"row": name, "time_ms": integer(data, "t" + name, 0, 86400000)}
        fill.update({key: number(data, key + name) for key in "qdv"})
        if fill["q"] == 0 or fill["q"] * fill["v"] < 0:
            raise ValueError("Each fill requires nonzero quantity and vega consistent with buy-positive/sell-negative signs")
        if fills and fill["time_ms"] < fills[-1]["time_ms"]:
            raise ValueError("Fills must be chronological")
        fills.append(fill)
    active = []
    anchor = fills[0]["time_ms"]
    history = []
    first = {"inclusive": None, "strict": None}
    enabled = "q" if metrics == "quantity-only" else "qdv"
    for index, fill in enumerate(fills):
        if mode == "first-fill-anchored":
            if fill["time_ms"] >= anchor + window:
                anchor = fill["time_ms"]
                active = []
            active.append(fill)
        else:
            active = [prior for prior in fills[:index + 1]
                      if prior["time_ms"] > fill["time_ms"] - window]
        totals = {
            "q": sum((abs(row["q"]) for row in active), Decimal(0)),
            "d": sum((row["d"] for row in active), Decimal(0)),
            "v": sum((row["v"] for row in active), Decimal(0)),
        }
        inclusive = [LABELS[key] for key in enabled if abs(totals[key]) >= limits[key]]
        strict = [LABELS[key] for key in enabled if abs(totals[key]) > limits[key]]
        for kind, causes in (("inclusive", inclusive), ("strict", strict)):
            if causes and first[kind] is None:
                first[kind] = fill
        history.append({
            "row": fill["row"], "time_ms": fill["time_ms"],
            "included_rows": [row["row"] for row in active],
            "gross_quantity": text(totals["q"]),
            "net_execution_delta": text(totals["d"]),
            "net_execution_vega": text(totals["v"]),
            "inclusive_causes": inclusive, "strict_causes": strict,
        })
    row_name = lambda fill: None if fill is None else fill["row"]
    unresolved = boundary == "unknown" and row_name(first["inclusive"]) != row_name(first["strict"])
    selected = None if unresolved else first["strict" if boundary == "strictly-above" else "inclusive"]
    position = opening + sum((fill["q"] for fill in fills), Decimal(0))
    last = history[-1]
    return {
        "status": "modelled",
        "counterHistory": history,
        "firstInclusiveRow": row_name(first["inclusive"]),
        "firstStrictRow": row_name(first["strict"]),
        "selectedTriggerRow": row_name(selected),
        "boundaryUnresolved": unresolved,
        "lastQuantity": last["gross_quantity"],
        "lastDelta": last["net_execution_delta"],
        "lastVega": last["net_execution_vega"],
        "remainingPosition": text(position),
        "currentPositionDelta": text(position * current_delta),
        "currentPositionVega": text(position * current_vega),
        "nominalFreezeEndMs": selected["time_ms"] + freeze if selected and freeze else None,
        "manualResetRequired": bool(selected and not freeze),
        "laterSuppliedFills": [fill["row"] for fill in fills if selected and fill["row"] > selected["row"]],
        "interpretation": "Supplied fills remain executed records. A candidate trigger does not close inventory or predict order outcomes.",
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("json_file", type=Path)
    parser.add_argument("--window-ms", type=int)
    parser.add_argument("--window-mode", choices=("first-fill-anchored", "trailing-comparison"))
    parser.add_argument("--boundary", choices=("unknown", "at-or-above", "strictly-above"))
    args = parser.parse_args()
    document = json.loads(args.json_file.read_text())
    inputs = dict(document.get("inputs", document))
    for key, value in (("windowMs", args.window_ms), ("windowMode", args.window_mode), ("boundary", args.boundary)):
        if value is not None:
            inputs[key] = str(value)
    print(json.dumps(calculate(inputs), indent=2))


if __name__ == "__main__":
    main()
