"""
general_analysis 전체 파이프라인 (지표·캔들·한 봉 특징).
"""

from __future__ import annotations

import pandas as pd

from deepcoin.common.candle_features import compute_bar_features
from deepcoin.analysis.general_analysis_candles import (
    general_analysis_apply_candles,
    general_analysis_candle_columns,
)
from deepcoin.analysis.general_analysis_chart import (
    general_analysis_apply_chart_bars,
    general_analysis_chart_columns,
    general_analysis_chart_metrics,
)
from deepcoin.analysis.general_analysis_context import general_analysis_apply_context_features
from deepcoin.analysis.general_analysis_harmonic import (
    general_analysis_harmonic_columns,
    general_analysis_harmonic_snapshot,
)
from deepcoin.analysis.general_analysis_volume import (
    general_analysis_volume_columns,
    general_analysis_volume_snapshot,
)
from deepcoin.analysis.general_analysis_core import ga_col, lookback_slice
from deepcoin.analysis.general_analysis_indicators import (
    general_analysis_apply_indicators,
    general_analysis_indicator_columns,
)
from deepcoin.analysis.general_analysis_patterns import (
    general_analysis_pattern_columns,
    general_analysis_pattern_snapshot,
)
from deepcoin.analysis.general_analysis_wave import (
    general_analysis_wave_columns,
    general_analysis_wave_snapshot,
)


def general_analysis_enrich_bars(
    df: pd.DataFrame,
    interval: int | None = None,
    *,
    full_context: bool = True,
) -> pd.DataFrame:
    """
    OHLCV → candle_features + ga 지표 + 캔들 + 차트 + (선택) lookback 컨텍스트.

    Args:
        df: raw OHLCV.
        interval: 분봉 간격. full_context=True일 때 필수.
        full_context: 패턴·VP·파동·하모닉 롤링 적용.

    Returns:
        전체 특징 컬럼 DataFrame.
    """
    base = compute_bar_features(df)
    out = general_analysis_apply_indicators(base)
    out = general_analysis_apply_candles(out)
    out = general_analysis_apply_chart_bars(out)
    if full_context and interval is not None:
        out = general_analysis_apply_context_features(out, interval)
    return out


def general_analysis_snapshot_at_bar(
    enriched: pd.DataFrame,
    ts: pd.Timestamp,
    interval: int,
) -> dict[str, object]:
    """
    타점 시각 직전 완성봉 + lookback 패턴·파동·차트 메타.

    Args:
        enriched: general_analysis_enrich_bars 결과.
        ts: 타점 시각.
        interval: 분봉 간격.

    Returns:
        flat dict (ga_ 키 + legacy bb/rsi where present).
    """
    win = lookback_slice(enriched, interval, ts)
    snap: dict[str, object] = {}
    if win.empty:
        return snap

    row = win.iloc[-1]

    legacy_cols = [
        "bb_pos",
        "RSI",
        "macd_hist",
        "stoch_k",
        "stoch_d",
        "macd_line",
        "macd_signal",
        "BB_Width",
    ]
    for c in legacy_cols:
        if c in row.index and not pd.isna(row[c]):
            snap[c] = float(row[c]) if isinstance(row[c], (int, float)) else row[c]

    for c in general_analysis_indicator_columns():
        col = ga_col(c)
        if col in row.index:
            v = row[col]
            snap[col] = None if pd.isna(v) else v

    for c in general_analysis_candle_columns():
        col = ga_col(c)
        if col in row.index:
            snap[col] = int(row[col]) if not pd.isna(row[col]) else 0

    pat_cols = [ga_col(c) for c in general_analysis_pattern_columns()]
    if pat_cols and pat_cols[0] in enriched.columns:
        for col in pat_cols:
            if col in row.index:
                snap[col] = row[col]
    else:
        snap.update(general_analysis_pattern_snapshot(win))

    wave_cols = [ga_col(c) for c in general_analysis_wave_columns()]
    if wave_cols and wave_cols[0] in enriched.columns:
        for col in wave_cols:
            if col in row.index:
                snap[col] = row[col]
    else:
        snap.update(general_analysis_wave_snapshot(win))

    snap.update(general_analysis_volume_snapshot(win))
    snap.update(general_analysis_harmonic_snapshot(win))
    snap.update(general_analysis_chart_metrics(win))

    return snap


def general_analysis_all_snapshot_keys() -> list[str]:
    """CSV 헤더용 전체 키 목록 (간격 접두사 제외)."""
    keys = list(legacy_snapshot_keys())
    keys += [ga_col(c) for c in general_analysis_indicator_columns()]
    keys += [ga_col(c) for c in general_analysis_candle_columns()]
    keys += [ga_col(c) for c in general_analysis_pattern_columns()]
    keys += [ga_col(c) for c in general_analysis_wave_columns()]
    keys += [ga_col(c) for c in general_analysis_chart_columns()]
    keys += [ga_col(c) for c in general_analysis_volume_columns()]
    keys += [ga_col(c) for c in general_analysis_harmonic_columns()]
    return keys


def legacy_snapshot_keys() -> list[str]:
    return ["bb_pos", "RSI", "macd_hist", "stoch_k", "stoch_d"]
