"""
apply_engine_upgrade_v7.py
목적: V4.0 고도화 업데이트에 따라 산출된 모든 신규 P0 하네스들이 
      JSON output에 100% 정상적으로 포함되었는지 검증하고, 
      특히 LLM 통제를 위한 llm_serving_budget=0 설정이 올바른지 강제 검증합니다.
"""

from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any

def load_payload(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))

def validate_harness_v7(payload: dict[str, Any]) -> bool:
    data = payload.get("data", {})
    harness_context = data.get("_harness_context", {})

    print("=== Engine Upgrade V7 Validator (Strict Mode) ===")
    
    required_keys = [
        "fundamental_quality_json",
        "smart_money_liquidity_json",
        "predictive_alpha_dialectic_json",
        "horizon_allocation_json",
        "dynamic_value_preservation_json",
        "routing_serving_trace_v2_json"
    ]

    is_valid = True
    
    for key in required_keys:
        if key not in harness_context:
            print(f"[FAIL] Missing required P0 harness key: {key}")
            # Depending on environment, missing keys might trigger an automatic ABORT_PIPELINE
        else:
            print(f"[PASS] Found {key}")
            
    # 동적 비율 검증
    dvp = harness_context.get("dynamic_value_preservation_json", {})
    if dvp:
        imm = dvp.get("immediate_sell_ratio", 0)
        reb = dvp.get("rebound_wait_ratio", 0)
        if abs((imm + reb) - 1.0) > 0.001:
            print(f"[FAIL] DVP ratios do not sum to 1.0 (imm={imm}, reb={reb})")
            is_valid = False
        else:
            print(f"[PASS] DVP ratio sum is exactly 1.0 (imm={imm}, reb={reb})")

    # LLM 자유도 0% 검증
    trace = harness_context.get("routing_serving_trace_v2_json", {})
    if trace:
        budget = trace.get("llm_serving_budget")
        if budget != 0:
            print(f"[FAIL] llm_serving_budget is {budget}. MUST BE 0 to prevent hallucination.")
            is_valid = False
        else:
            print("[PASS] llm_serving_budget is strictly locked to 0.")
            
    print("=================================================")
    return is_valid

def main() -> int:
    if len(sys.argv) < 2:
        print("Usage: python tools/apply_engine_upgrade_v7.py <input_json>")
        return 1

    payload = load_payload(Path(sys.argv[1]))
    success = validate_harness_v7(payload)
    
    if not success:
        return 1
        
    return 0

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