#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]

def parse_number(text: str) -> float:
    # Remove commas and convert to float
    clean = text.replace(",", "").strip()
    return float(clean)

def check_value(packet_val: Any, report_vals: list[float | str], is_rate: bool = False) -> tuple[str, list[str]]:
    mismatches = []
    if packet_val is None:
        return "PASS", mismatches
    
    for val in report_vals:
        if is_rate:
            try:
                p_v = float(packet_val)
                r_v = float(val)
                if abs(p_v - r_v) > 0.1: # 0.1%p limit
                    mismatches.append(f"packet={p_v}% vs report={r_v}%")
            except ValueError:
                mismatches.append(f"packet={packet_val} vs report={val} (parse error)")
        else:
            if isinstance(packet_val, (int, float)):
                try:
                    r_v = float(val)
                    if abs(float(packet_val) - r_v) > 1.0: # 1 KRW limit
                        mismatches.append(f"packet={packet_val} vs report={r_v}")
                except ValueError:
                    mismatches.append(f"packet={packet_val} vs report={val} (parse error)")
            else:
                if str(packet_val).strip() != str(val).strip():
                    mismatches.append(f"packet={packet_val} vs report={val}")
                    
    status = "FAIL" if mismatches else "PASS"
    return status, mismatches

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--packet", default="Temp/final_decision_packet_active.json")
    ap.add_argument("--report", default="Temp/operational_report.json")
    args = ap.parse_args()

    packet_path = ROOT / args.packet
    report_path = ROOT / args.report

    if not packet_path.exists():
        print(f"Packet file not found: {packet_path}")
        return 1
    if not report_path.exists():
        print(f"Report file not found: {report_path}")
        return 1

    packet = json.loads(packet_path.read_text(encoding="utf-8"))
    report_data = json.loads(report_path.read_text(encoding="utf-8"))

    # Extract markdown content from all sections
    report_text = ""
    if isinstance(report_data, dict) and "sections" in report_data:
        report_text = "\n".join([str(s.get("markdown", "")) for s in report_data["sections"] if isinstance(s, dict)])
    else:
        report_text = str(report_data)

    metrics = packet.get("canonical_metrics", {})
    
    # 1. Total Asset
    total_asset_krw = metrics.get("total_asset_krw", {}).get("value")
    # 2. Cash Shortfall
    cash_shortfall_min_krw = metrics.get("cash_shortfall_min_krw", {}).get("value")
    # 3. Cash Recovered
    cash_recovered_krw = metrics.get("cash_recovered_krw", {}).get("value") or metrics.get("cash_recovered", {}).get("value")
    # 4. Execution Gate
    final_execution_gate = metrics.get("final_execution_gate", {}).get("value") or packet.get("routing_serving", {}).get("global_execution_gate", {}).get("value")
    # 5. HTS Order Count
    hts_order_count = metrics.get("hts_order_count", {}).get("value")

    # Regular expression searches
    # Total Asset
    asset_matches = []
    # e.g., 총자산 | **394,191,813원** or 포트폴리오 총자산: 394,191,813원
    for m in re.finditer(r"(?:총자산|포트폴리오 총자산)\s*(?:\||:)?\s*\*\*?([\d,]+)\s*원\*\*?", report_text):
        asset_matches.append(parse_number(m.group(1)))
    
    # Cash Shortfall
    shortfall_matches = []
    # e.g., 현금 부족액 | **59,128,772원** or 현금 59,128,772원 부족 or 즉시 현금 확보 (59,128,772원 부족) or 현금회복 원장 참조 (59,128,772원 부족)
    for m in re.finditer(r"(?:현금 부족액|현금부족|현금\s*\*\*?[\d,]+원\*\*?\s*부족|현금회복 원장 참조|즉시 현금 확보|현금\s*확보)\s*(?:\||:)?\s*\(?\s*\*\*?([\d,]+)\s*원\s*(?:부족)?\*\*?", report_text):
        shortfall_matches.append(parse_number(m.group(1)))
    
    # Cash Recovered / 정산현금
    recovered_matches = []
    # e.g., 정산현금 | 394,191,813원 / 0원
    # Let's extract from: 주식 평가액 / 정산현금 | 394,191,813원 / 0원
    for m in re.finditer(r"(?:정산현금|현금회복)\s*(?:\||:)?\s*(?:[\d,]+원\s*/\s*)?\*\*?([\d,]+)\s*원\*\*?", report_text):
        recovered_matches.append(parse_number(m.group(1)))
        
    # Execution Gate
    gate_matches = []
    # e.g., 실행 게이트 | 🟢 **AUDIT_ONLY**
    for m in re.finditer(r"(?:final_execution_gate|실행 게이트|신규매수)\s*(?:\||:)?\s*(?:[^\w]*)\*\*?([A-Z_]+)\*\*?", report_text):
        gate_matches.append(m.group(1).strip())
        
    # HTS Order Count
    order_count_matches = []
    # e.g., hts_order_count: **0**
    for m in re.finditer(r"(?:hts_order_count|HTS 주문\s*수|주문\s*수)\s*(?:\||:)?\s*\*\*?(\d+)\*\*?", report_text):
        order_count_matches.append(int(m.group(1)))

    all_errors = []
    
    asset_status, asset_errs = check_value(total_asset_krw, asset_matches)
    all_errors.extend(asset_errs)
    
    shortfall_status, shortfall_errs = check_value(cash_shortfall_min_krw, shortfall_matches)
    all_errors.extend(shortfall_errs)
    
    recovered_status, recovered_errs = check_value(cash_recovered_krw, recovered_matches)
    all_errors.extend(recovered_errs)
    
    gate_status, gate_errs = check_value(final_execution_gate, gate_matches)
    all_errors.extend(gate_errs)
    
    order_status, order_errs = check_value(hts_order_count, order_count_matches)
    all_errors.extend(order_errs)

    gate_result = "PASS" if not all_errors else "FAIL"

    result = {
        "formula_id": "REPORT_NUMERIC_CONSISTENCY_GUARD_V2",
        "total_asset_krw": {
            "packet_value": total_asset_krw,
            "report_matches": asset_matches,
            "status": asset_status
        },
        "cash_shortfall_min_krw": {
            "packet_value": cash_shortfall_min_krw,
            "report_matches": shortfall_matches,
            "status": shortfall_status
        },
        "cash_recovered_krw": {
            "packet_value": cash_recovered_krw,
            "report_matches": recovered_matches,
            "status": recovered_status
        },
        "final_execution_gate": {
            "packet_value": final_execution_gate,
            "report_matches": gate_matches,
            "status": gate_status
        },
        "hts_order_count": {
            "packet_value": hts_order_count,
            "report_matches": order_count_matches,
            "status": order_status
        },
        "errors": all_errors,
        "gate": gate_result
    }

    out_path = ROOT / "Temp" / "report_numeric_consistency_guard_v2.json"
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")

    print(json.dumps(result, ensure_ascii=False, indent=2))
    
    if gate_result == "FAIL":
        print("FAIL_CROSS_SECTION_NUMERIC_CONFLICT: Numeric inconsistency detected between packet and report.")
        return 1
    
    return 0

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