#!/usr/bin/env python3
"""1단계: Ground Truth — 사후 최적 스윙 매수·매도 타점 (1매수·1매도 레그)."""

from __future__ import annotations

import argparse
import logging
import sys
from dataclasses import replace
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))

from deepcoin.config import Settings, load_settings
from deepcoin.data.intervals import interval_label
from deepcoin.ground_truth.chart import render_ground_truth_chart
from deepcoin.ground_truth.ground_truth import GtParams, build_ground_truth, save_ground_truth

TIER_DESCRIPTIONS = {
    "v1": "스윙만 (최소 매수·매도)",
    "v2": "스윙 + 눌림목",
    "v3": "스윙 + 눌림목 + 돌파 + 다이버전스",
}


def _configure_logging(verbose: bool) -> None:
    """로깅 레벨을 설정한다."""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s [%(levelname)s] %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )


def _base_params(settings: Settings, args: argparse.Namespace) -> GtParams:
    """CLI·환경 설정을 반영한 공통 GT 파라미터."""
    return GtParams(
        interval_min=args.interval or settings.gt_interval_min,
        lookback_days=args.days or settings.gt_lookback_days,
        zigzag_reversal_pct=args.zigzag or settings.gt_zigzag_reversal_pct,
        min_leg_pct=args.min_leg or settings.gt_min_leg_pct,
        pullback_min_pct=settings.gt_pullback_min_pct,
        pullback_local_order=settings.gt_pullback_local_order,
        breakout_buffer_pct=settings.gt_breakout_buffer_pct,
        breakout_consolidation_bars=settings.gt_breakout_consolidation_bars,
        breakout_min_rally_pct=settings.gt_breakout_min_rally_pct,
        div_local_order=settings.gt_div_local_order,
        div_min_bars_between=settings.gt_div_min_bars_between,
        div_min_rsi_diff=settings.gt_div_min_rsi_diff,
        div_min_future_move_pct=settings.gt_div_min_future_move_pct,
    )


def _tier_targets(settings: Settings, tier_arg: str) -> list[tuple[str, Path, Path]]:
    """생성할 티어 목록 (tier, json_path, chart_path)."""
    all_tiers: dict[str, tuple[Path, Path]] = {
        "v1": (settings.ground_truth_v1_file, settings.ground_truth_chart_v1_file),
        "v2": (settings.ground_truth_v2_file, settings.ground_truth_chart_v2_file),
        "v3": (settings.ground_truth_file, settings.ground_truth_chart_v3_file),
    }
    if tier_arg == "all":
        return [(t, *paths) for t, paths in all_tiers.items()]
    return [(tier_arg, *all_tiers[tier_arg])]


def _print_tier_summary(
    tier: str,
    result: dict[str, Any],
    json_path: Path,
    chart_path: Path | None,
) -> None:
    """티어별 GT 요약을 출력한다."""
    summary = result["summary"]
    meta = result["meta"]
    pnl = result["pnl"]

    print(f"\n=== Ground Truth {tier.upper()} ({TIER_DESCRIPTIONS[tier]}) ===")
    print(f"대상: {meta['symbol']} ({meta['interval_label']})")
    print(f"GT·수익 기간: {meta['data_from']} ~ {meta['data_to']} ({meta['bar_count']}봉)")
    print(f"피벗: {meta['pivot_count']}개 → 레그: {summary['leg_count']}개")
    print(
        f"매수 타점: {summary['buy_count']}개 "
        f"(눌림 {summary.get('pullback_buy_count', 0)} / 돌파 {summary.get('breakout_buy_count', 0)} "
        f"/ 다이버전스 {summary.get('divergence_buy_count', 0)}) "
        f"/ 매도: {summary['sell_count']}개 (다이버전스 {summary.get('divergence_sell_count', 0)})"
    )
    print(f"레그 수익률 — 평균: {summary['avg_leg_pct']}%, 최대: {summary['max_leg_pct']}%")

    period = ""
    if pnl.get("period_from"):
        period = f" ({pnl['period_from'][:10]} ~ {pnl['period_to'][:10]})"
    print(f"누적 수익{period}: {pnl['final_cash_krw']:,.0f}원 ({pnl['total_return_pct']:+.2f}%)")
    print(f"JSON: {json_path}")
    if chart_path:
        print(f"차트: {chart_path}")


def main() -> int:
    """CLI 진입점."""
    parser = argparse.ArgumentParser(description="Ground Truth 스윙 레그 생성 (1단계)")
    parser.add_argument("--interval", type=int, default=None, help="GT 인터벌(분)")
    parser.add_argument("--days", type=int, default=None, help="GT·타점 기간(일). 기본 730(2년)")
    parser.add_argument("--zigzag", type=float, default=None, help="ZigZag 되돌림 %%")
    parser.add_argument("--min-leg", type=float, default=None, help="최소 레그 수익률 %%")
    parser.add_argument("--no-chart", action="store_true", help="HTML 차트 생략")
    parser.add_argument(
        "--tier",
        choices=("v1", "v2", "v3", "all"),
        default="all",
        help="생성할 GT 버전 (v1=스윙만, v2=+눌림, v3=전체, all=3종)",
    )
    parser.add_argument("-v", "--verbose", action="store_true")
    args = parser.parse_args()

    _configure_logging(args.verbose)
    settings = load_settings()
    base = _base_params(settings, args)
    tiers = _tier_targets(settings, args.tier)

    logging.info(
        "GT 생성: %s %s, %s일, ZigZag=%s%%, min_leg=%s%%, 초기=%s원, tier=%s",
        settings.symbol,
        interval_label(base.interval_min),
        base.lookback_days,
        base.zigzag_reversal_pct,
        base.min_leg_pct,
        f"{settings.gt_initial_cash_krw:,.0f}",
        args.tier,
    )

    print("\n=== Ground Truth 완료 (1단계 벤치마크) ===")
    print(f"차트·타점 표시: 최근 {settings.download_days}일")

    for tier, json_path, chart_path in tiers:
        params = replace(base, chart_tier=tier)
        result = build_ground_truth(
            db_path=settings.db_path,
            symbol=settings.symbol,
            coin_name=settings.coin_name,
            params=params,
            initial_cash_krw=settings.gt_initial_cash_krw,
            fee_rate=settings.gt_trading_fee_rate,
        )
        save_ground_truth(result, json_path)

        rendered: Path | None = None
        if not args.no_chart:
            rendered = render_ground_truth_chart(
                db_path=settings.db_path,
                symbol=settings.symbol,
                gt_result=result,
                output_path=chart_path,
                chart_lookback_days=settings.download_days,
            )

        _print_tier_summary(tier, result, json_path, rendered)

    return 0


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