#!/usr/bin/env python3
"""Hybrid DD tier 임계값 train 캘리브레이션 (Option C 2차)."""
import runpy
from pathlib import Path

runpy.run_path(str(Path(__file__).resolve().parent / "_bootstrap.py"))

import pandas as pd

from config import CHART_LOOKBACK_DAYS, MATCH_PRIMARY_INTERVAL, SYMBOL
from deepcoin.data.mtf_bb import load_frames_from_db
from deepcoin.ground_truth.ground_truth import load_ground_truth
from deepcoin.ground_truth.hybrid_dd_calibrate import run_and_save_calibration
from deepcoin.matching.load_rules import load_matched_rules
from deepcoin.ops.monitor import Monitor
from deepcoin.paths import MATCHING_FIRE_OUTCOMES, MATCHING_HYBRID_DD_CALIBRATION_JSON


def main() -> None:
    """monitor 발화 + OHLC로 DD tier 캘리브레이션."""
    outcomes = pd.read_csv(MATCHING_FIRE_OUTCOMES)
    matched = load_matched_rules()
    monitor_ids = {r["rule_id"] for r in matched.get("monitor_rules", [])}
    fires = outcomes[outcomes["rule_id"].isin(monitor_ids)]

    mon = Monitor(cooldown_file=None)
    ohlc = load_frames_from_db(mon, SYMBOL, lookback_days=CHART_LOOKBACK_DAYS)[
        MATCH_PRIMARY_INTERVAL
    ]
    gt = load_ground_truth() or {}
    mark = (gt.get("summary") or {}).get("mark_price")

    result = run_and_save_calibration(
        fires,
        ohlc,
        outcomes=outcomes,
        last_price=float(mark) if mark else None,
    )
    best = result.get("best_params") or {}
    metrics = result.get("best_metrics") or {}
    print(f"[hybrid DD] 저장: {MATCHING_HYBRID_DD_CALIBRATION_JSON}")
    print(
        f"[hybrid DD] best dd_large={best.get('dd_large_pct')} "
        f"dd_medium={best.get('dd_medium_pct')} "
        f"train={metrics.get('train_pnl_pct')}% "
        f"holdout={metrics.get('holdout_pnl_pct')}% "
        f"full={metrics.get('full_pnl_pct')}%"
    )


if __name__ == "__main__":
    main()
