param(
  [string]$JsonPath = ".\GatherTradingData.json",
  [string]$ReportPath = ".\Temp\operational_report.md",
  [string]$HarnessJsonPath = ".\Temp\prediction_improvement_harness.json",
  [string]$ResultJsonPath = ".\Temp\engine_harness_gate_result.json"
)

$ErrorActionPreference = "Stop"

python .\tools\update_proposal_evaluation_history.py --json $JsonPath --history .\Temp\proposal_evaluation_history.json
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

python .\tools\build_rule_lifecycle_policy.py --history .\Temp\proposal_evaluation_history.json --output .\Temp\rule_lifecycle_policy.json
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

python .\tools\build_strategy_harness_v2.py --json $JsonPath --output .\Temp\strategy_harness_v2.json
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

# ── [Phase-1] 결정론 도구 순차 실행 ──────────────────────────────────────────
# VALUE_PRESERVATION_SCORER_V1 (SMART_CASH_RECOVERY_V3 입력으로 사용)
python .\tools\build_value_preservation_scorer_v1.py --json $JsonPath --out .\Temp\value_preservation_scorer_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "VALUE_PRESERVATION_SCORER_V1 FAIL — 계속 진행" }

# SMART_CASH_RECOVERY_V3
python .\tools\build_smart_cash_recovery_v3.py --json $JsonPath --vps .\Temp\value_preservation_scorer_v1.json --out .\Temp\smart_cash_recovery_v3.json
if ($LASTEXITCODE -ne 0) { Write-Warning "SMART_CASH_RECOVERY_V3 FAIL — 계속 진행" }

# RATCHET_TRAILING_GENERAL_V1
python .\tools\build_ratchet_trailing_general_v1.py --json $JsonPath --out .\Temp\ratchet_trailing_general_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "RATCHET_TRAILING_GENERAL_V1 FAIL — 계속 진행" }

# EJCE_VIEW_RENDERER_V1
python .\tools\build_ejce_view_renderer_v1.py --json $JsonPath --out .\Temp\ejce_view_renderer_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "EJCE_VIEW_RENDERER_V1 FAIL — 계속 진행" }

# ROUTING_EXECUTION_LOG_TABLE_V1
python .\tools\build_routing_execution_log_v1.py --json $JsonPath --out .\Temp\routing_execution_log_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "ROUTING_EXECUTION_LOG_TABLE_V1 FAIL — 계속 진행" }

# ── 1차 렌더 (Phase 4~5 도구가 최신 보고서를 읽어야 하므로 미리 실행) ───────────
# validate_engine_harness_gate.py 내부에서 2차 렌더(최종)가 다시 실행됨 (멱등)
dotnet run --project .\src\dotnet\QuantEngine.Tools\QuantEngine.Tools.csproj -- report --packet=Temp/final_decision_packet_active.json --out=Temp/operational_report.json
if ($LASTEXITCODE -ne 0) { Write-Warning "RENDER_OPERATIONAL_REPORT(pre-phase45) FAIL — 계속 진행" }

# BLANK_CELL_AUDIT_V1 (1차 렌더 이후 실행 — 게이트 검증기에서 2차 재실행됨)
python .\tools\build_blank_cell_audit_v1.py --report .\Temp\operational_report.json --out .\Temp\blank_cell_audit_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "BLANK_CELL_AUDIT_V1 FAIL — 계속 진행 (WARN_ONLY 기간)" }
# ─────────────────────────────────────────────────────────────────────────────

# ── [Phase-2] 펀더멘털 신호 ────────────────────────────────────────────────────
# FUNDAMENTAL_RAW_INGEST_V1 (data_feed + 네이버 fallback)
python .\tools\ingest_fundamental_raw.py --json $JsonPath --no-naver --out .\Temp\fundamental_raw_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "FUNDAMENTAL_RAW_INGEST_V1 FAIL — 계속 진행" }

# FUNDAMENTAL_MULTIFACTOR_V3
python .\tools\build_fundamental_multifactor_v3.py --raw .\Temp\fundamental_raw_v1.json --json $JsonPath --out .\Temp\fundamental_multifactor_v3.json
if ($LASTEXITCODE -ne 0) { Write-Warning "FUNDAMENTAL_MULTIFACTOR_V3 FAIL — 계속 진행" }

# HORIZON_CLASSIFICATION_V1 (fundamental_multifactor_v3 의존)
python .\tools\build_horizon_classification_v1.py --json $JsonPath --fund .\Temp\fundamental_multifactor_v3.json --out .\Temp\horizon_classification_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "HORIZON_CLASSIFICATION_V1 FAIL — 계속 진행" }
# ─────────────────────────────────────────────────────────────────────────────

# ── [Phase-3] 수급·유동성·PAC ─────────────────────────────────────────────────
# SMART_MONEY_FLOW_SIGNAL_V2
python .\tools\build_smart_money_flow_signal_v2.py --json $JsonPath --out .\Temp\smart_money_flow_signal_v2.json
if ($LASTEXITCODE -ne 0) { Write-Warning "SMART_MONEY_FLOW_SIGNAL_V2 FAIL — 계속 진행" }

# LIQUIDITY_FLOW_SIGNAL_V1
python .\tools\build_liquidity_flow_signal_v1.py --json $JsonPath --out .\Temp\liquidity_flow_signal_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "LIQUIDITY_FLOW_SIGNAL_V1 FAIL — 계속 진행" }

# PORTFOLIO_ALPHA_CONFIDENCE_PER_TICKER_V1 (fundamental_multifactor_v3 의존)
python .\tools\build_portfolio_alpha_confidence_per_ticker_v1.py --json $JsonPath --fund .\Temp\fundamental_multifactor_v3.json --out .\Temp\portfolio_alpha_confidence_per_ticker_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "PORTFOLIO_ALPHA_CONFIDENCE_PER_TICKER_V1 FAIL — 계속 진행" }

# MARKET_SHARE_SIGNAL_V2
python .\tools\build_market_share_signal_v2.py --json $JsonPath --out .\Temp\market_share_signal_v2.json
if ($LASTEXITCODE -ne 0) { Write-Warning "MARKET_SHARE_SIGNAL_V2 FAIL — 계속 진행" }
# ─────────────────────────────────────────────────────────────────────────────

# ── [Phase-2B] 이익·성장·현금흐름 시그널 ──────────────────────────────────────
# EARNINGS_QUALITY_SIGNAL_V1
python .\tools\build_earnings_quality_signal_v1.py --raw .\Temp\fundamental_raw_v1.json --json $JsonPath --out .\Temp\earnings_quality_signal_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "EARNINGS_QUALITY_SIGNAL_V1 FAIL — 계속 진행" }

# GROWTH_RATE_SIGNAL_V1
python .\tools\build_growth_rate_signal_v1.py --raw .\Temp\fundamental_raw_v1.json --json $JsonPath --out .\Temp\growth_rate_signal_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "GROWTH_RATE_SIGNAL_V1 FAIL — 계속 진행" }

# CASHFLOW_QUALITY_SIGNAL_V1
python .\tools\build_cashflow_quality_signal_v1.py --raw .\Temp\fundamental_raw_v1.json --json $JsonPath --out .\Temp\cashflow_quality_signal_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "CASHFLOW_QUALITY_SIGNAL_V1 FAIL — 계속 진행" }
# ─────────────────────────────────────────────────────────────────────────────

# ── [Phase-4~5] 실측 반영 + 신규 하네스 7종 ──────────────────────────────────
# TRADE_QUALITY_FROM_T5_V1 (운영 T5 거래품질 실측)
python .\tools\build_trade_quality_from_t5_v1.py --hist .\Temp\proposal_evaluation_history.json --out .\Temp\trade_quality_from_t5_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "TRADE_QUALITY_FROM_T5_V1 FAIL — 계속 진행" }

# OUTCOME_QUALITY_SCORE_V1 (T5 proxy 반영 재산출)
python .\tools\build_outcome_quality_score_v1.py --json $JsonPath --out .\Temp\outcome_quality_score_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "OUTCOME_QUALITY_SCORE_V1 FAIL — 계속 진행" }

# PREDICTION_ACCURACY_HARNESS_V2 (운영 예측 정확도 회전윈도)
python .\tools\build_prediction_accuracy_harness_v2.py --hist .\Temp\proposal_evaluation_history.json --out .\Temp\prediction_accuracy_harness_v2.json
if ($LASTEXITCODE -ne 0) { Write-Warning "PREDICTION_ACCURACY_HARNESS_V2 FAIL — 계속 진행" }

# MACRO_EVENT_TICKER_IMPACT_V1 (거시이벤트 종목별 영향)
python .\tools\build_macro_event_ticker_impact_v1.py --json $JsonPath --out .\Temp\macro_event_ticker_impact_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "MACRO_EVENT_TICKER_IMPACT_V1 FAIL — 계속 진행" }

# SELL_WATERFALL_ENGINE_V2 (슬리피지+유동성+에스컬레이션)
python .\tools\build_sell_waterfall_engine_v2.py --json $JsonPath --out .\Temp\sell_waterfall_engine_v2.json
if ($LASTEXITCODE -ne 0) { Write-Warning "SELL_WATERFALL_ENGINE_V2 FAIL — 계속 진행" }

# LLM_NARRATIVE_TEMPLATE_LOCK_V1 (서술 금지어휘 잠금)
python .\tools\build_llm_narrative_template_lock_v1.py --report .\Temp\operational_report.json --out .\Temp\llm_narrative_template_lock_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "LLM_NARRATIVE_TEMPLATE_LOCK_V1 FAIL — 계속 진행" }

# EJCE_DIVERGENCE_AUDIT_V1 (3관점 합의 진정성)
python .\tools\build_ejce_divergence_audit_v1.py --json $JsonPath --out .\Temp\ejce_divergence_audit_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "EJCE_DIVERGENCE_AUDIT_V1 FAIL — 계속 진행" }

# PREDICTIVE_ALPHA_REPORT_LOCK_V2 (PA1 정반합 보고 잠금)
python .\tools\build_predictive_alpha_report_lock_v2.py --json $JsonPath --out .\Temp\predictive_alpha_report_lock_v2.json
if ($LASTEXITCODE -ne 0) { Write-Warning "PREDICTIVE_ALPHA_REPORT_LOCK_V2 FAIL — 계속 진행" }
# ─────────────────────────────────────────────────────────────────────────────

# ── [Phase-6] 판단 결정론 계층 (Verdict-Lock 포함) ────────────────────────────
# Phase-6 실행 순서: smart_money_liquidity → data_quality_reconciliation → final_judgment → render(2차) → verdict_lock

# DATA_QUALITY_RECONCILIATION_V1 (invest_quality 충돌 탐지)
python .\tools\build_data_quality_reconciliation_v1.py --json $JsonPath --integrity .\Temp\data_integrity_score_v1.json --out .\Temp\data_quality_reconciliation_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "DATA_QUALITY_RECONCILIATION_V1 FAIL — 계속 진행" }

# SMART_MONEY_LIQUIDITY_GATE_V1 (SM001~003 결정론)
python .\tools\build_smart_money_liquidity_gate_v1.py --json $JsonPath --out .\Temp\smart_money_liquidity_gate_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "SMART_MONEY_LIQUIDITY_GATE_V1 FAIL — 계속 진행" }

# FINAL_JUDGMENT_GATE_V1 (판단 결정론 계층 — 키스톤)
python .\tools\build_final_judgment_gate_v1.py --json $JsonPath --out .\Temp\final_judgment_gate_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "FINAL_JUDGMENT_GATE_V1 FAIL — 계속 진행" }

# 2차 렌더 (final_judgment_table + investment_quality_headline 섹션 포함)
dotnet run --project .\src\dotnet\QuantEngine.Tools\QuantEngine.Tools.csproj -- report --packet=Temp/final_decision_packet_active.json --out=Temp/operational_report.json
if ($LASTEXITCODE -ne 0) { Write-Warning "RENDER_OPERATIONAL_REPORT(phase6-final) FAIL — 계속 진행" }

# VERDICT_CONSISTENCY_LOCK_V1 (render 이후 실행 — 최신 보고서 기준 검증)
python .\tools\build_verdict_consistency_lock_v1.py --fj .\Temp\final_judgment_gate_v1.json --report .\Temp\operational_report.json --out .\Temp\verdict_consistency_lock_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "VERDICT_CONSISTENCY_LOCK_V1 FAIL — 계속 진행" }
# ─────────────────────────────────────────────────────────────────────────────

# ALPHA_FEEDBACK_LOOP_V2 (T5 기반 AFL — 즉시 동작)
python .\tools\build_alpha_feedback_loop_v2.py --hist .\Temp\proposal_evaluation_history.json --out .\Temp\alpha_feedback_loop_v2.json
if ($LASTEXITCODE -ne 0) { Write-Warning "ALPHA_FEEDBACK_LOOP_V2 FAIL -- 계속 진행" }

# ALPHA_LEAD_THRESHOLD_OPTIMIZER_V1 (진입점수 최적화 분석)
python .\tools\build_alpha_lead_threshold_optimizer_v1.py --hist .\Temp\proposal_evaluation_history.json --out .\Temp\alpha_lead_threshold_optimizer_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "ALPHA_LEAD_THRESHOLD_OPTIMIZER FAIL -- 계속 진행" }

# ── [Phase-7] 단일 진실원천 + 교차섹션 정합성 게이트 (CHECK_89~92) ──────────
# CANONICAL_METRICS_V1 — 정규 지표 단일 원천 산출
python .\tools\build_canonical_metrics_v1.py
if ($LASTEXITCODE -ne 0) { Write-Warning "CANONICAL_METRICS_V1 FAIL — 계속 진행" }

# 3차 렌더 (canonical 값이 주입된 최신 보고서 생성)
dotnet run --project .\src\dotnet\QuantEngine.Tools\QuantEngine.Tools.csproj -- report --packet=Temp/final_decision_packet_active.json --out=Temp/operational_report.json
if ($LASTEXITCODE -ne 0) { Write-Warning "RENDER_OPERATIONAL_REPORT(phase7-canonical) FAIL — 계속 진행" }

# CROSS_SECTION_CONSISTENCY_V1 — 교차섹션 정합성 게이트 (render 이후 실행)
python .\tools\build_cross_section_consistency_v1.py
if ($LASTEXITCODE -ne 0) { Write-Warning "CROSS_SECTION_CONSISTENCY_V1 FAIL — 계속 진행" }

# ALGORITHM_GUIDANCE_PROOF_V1 — 지침 증명 재산출 (최신 보고서 기준)
python .\tools\build_algorithm_guidance_proof_v1.py --json $JsonPath --out .\Temp\algorithm_guidance_proof_v1.json
if ($LASTEXITCODE -ne 0) { Write-Warning "ALGORITHM_GUIDANCE_PROOF_V1 FAIL — 계속 진행" }
# ─────────────────────────────────────────────────────────────────────────────

python .\tools\validate_engine_harness_gate.py `
  --json $JsonPath `
  --report $ReportPath `
  --harness-json $HarnessJsonPath `
  --result-json $ResultJsonPath

exit $LASTEXITCODE
