#!/usr/bin/env python3
"""P5_01: 뒷북 매수·설거지 차단 — alpha_lead + pre_distribution 게이트"""

from __future__ import annotations
import json, sys
from pathlib import Path
from datetime import datetime

ROOT = Path(__file__).resolve().parent.parent
OUTPUT = ROOT / "Temp" / "p5_01_anti_chase_spec.json"

if sys.stdout.encoding and sys.stdout.encoding.lower() not in ("utf-8", "utf8"):
    sys.stdout = open(sys.stdout.fileno(), mode="w", encoding="utf-8", buffering=1)

def build_spec() -> dict:
    return {
        "schema_version": "anti_late_entry_v1",
        "generated_at": datetime.now().isoformat(),
        "problem": "late_chase_status=DEGRADE_BUY_PERMISSION 발동중. 뒷북+설거지 차단 필요",
        "solution_1_alpha_lead_entry": {
            "name": "ALPHA_LEAD_ENTRY_GATE_V1",
            "rules": {
                "pilot_allowed": "alpha_lead_score >= 75 AND lead_entry_state == PILOT_ALLOWED",
                "add_on_allowed": "pilot_pnl >= 0 AND flow_confirmed=true AND breakout_volume_confirmed=true",
                "pullback_allowed": "confirmed_add_on=true AND pullback_to_ma20_or_atr_band=true"
            },
            "tranche_order": ["T1(30%)", "T2(30%)", "T3(40%)"],
            "forbidden": ["CONFIRMED_ADD_ON 없이 T3 진입", "분위기로 PILOT 승격"]
        },
        "solution_2_pre_distribution_gate": {
            "name": "PRE_DISTRIBUTION_EARLY_WARNING_V1",
            "block_buy_if": [
                "distribution_risk_score >= 70",
                "price_up_volume_down == true",
                "foreign_inst_net_sell_5d == true",
                "candle_upper_tail_cluster == true"
            ]
        },
        "implementation": [
            "spec/exit/pre_distribution_gate.yaml",
            "gas_data_feed.gs: calcAlphaLeadV1_(), calcDistributionRiskV1_()",
            "tools/validate_alpha_execution_harness.py"
        ]
    }

def main() -> int:
    print("=" * 70)
    print("  P5_01: 뒷북 매수·설거지 차단")
    print("=" * 70)
    spec = build_spec()
    OUTPUT.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"\n✓ 뒷북 차단 스펙 저장: {OUTPUT.name}")
    print(f"  1. Alpha Lead Entry: alpha_lead_score >= 75")
    print(f"  2. Pre-Distribution: distribution_risk >= 70 → BUY 블록")
    print(f"  3. Tranche 순서: T1(30%) → T2(30%) → T3(40%)")
    return 0

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