from __future__ import annotations

import argparse
import json

from v7_hardening_common import ROOT, TEMP, load_json, save_json, sha256_hex


DEFAULT_OUT = TEMP / "final_context_for_llm_v2.json"


def _value(item):
    if isinstance(item, dict) and "value" in item:
        return item.get("value")
    return item


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=str(DEFAULT_OUT))
    args = ap.parse_args()

    packet = load_json(TEMP / "final_decision_packet_active.json") or load_json(TEMP / "final_execution_decision_v2.json")
    fed = load_json(TEMP / "final_execution_decision_v2.json")
    scr = load_json(TEMP / "smart_cash_recovery_v7.json") or load_json(TEMP / "smart_cash_recovery_v6.json") or load_json(TEMP / "smart_cash_recovery_v5.json")
    truth = load_json(TEMP / "operational_truth_score_v1.json")
    result = {
        "formula_id": "FINAL_CONTEXT_FOR_LLM_V2",
        "source_path": "Temp/final_decision_packet_active.json",
        "input_hash": sha256_hex(TEMP / "final_decision_packet_active.json") if (TEMP / "final_decision_packet_active.json").exists() else "",
        "global_execution_gate": packet.get("meta", {}).get("engine_gate", fed.get("global_execution_gate", "AUDIT_ONLY")),
        "llm_allowed_actions": fed.get("llm_allowed_actions", ["AUDIT_ONLY"]),
        "numbers": {
            "cash_shortfall_min_krw": {
                "value": _value(packet.get("canonical_metrics", {}).get("cash_shortfall_min_krw", scr.get("cash_shortfall_min_krw"))),
                "source_path": "Temp/final_decision_packet_active.json",
                "formula_id": "CANONICAL_ARTIFACT_RESOLVER_V2",
            },
            "cash_recovered_krw": {
                "value": _value(packet.get("canonical_metrics", {}).get("cash_recovered_krw", scr.get("cash_recovered_krw"))),
                "source_path": "Temp/final_decision_packet_active.json",
                "formula_id": "FINAL_DECISION_PACKET_V4",
            },
            "performance_readiness_score": {
                "value": truth.get("performance_readiness_score"),
                "source_path": "Temp/operational_truth_score_v1.json",
                "formula_id": "OPERATIONAL_TRUTH_SCORE_V1",
            },
        },
        "required_copy_only_fields": [
            "global_execution_gate",
            "llm_allowed_actions",
            "cash_shortfall_min_krw",
            "cash_recovered_krw",
            "performance_readiness_score",
        ],
        "numeric_generation_allowed": 0,
    }
    save_json(args.out, result)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
