"""
general_analysis lookback 컨텍스트 특징 (패턴·파동·VP·하모닉) 봉별 적용.
"""

from __future__ import annotations

import pandas as pd

from deepcoin.analysis.general_analysis_config import CONTEXT_TAIL_ROWS, LOOKBACK_BARS
from deepcoin.analysis.general_analysis_core import ga_col
from deepcoin.analysis.general_analysis_harmonic import (
    general_analysis_harmonic_columns,
    general_analysis_harmonic_snapshot,
)
from deepcoin.analysis.general_analysis_patterns import general_analysis_apply_patterns_to_bars
from deepcoin.analysis.general_analysis_volume import (
    general_analysis_volume_columns,
    general_analysis_volume_snapshot,
)
from deepcoin.analysis.general_analysis_wave import general_analysis_apply_wave_to_bars


def general_analysis_apply_volume_to_bars(
    df: pd.DataFrame,
    interval: int,
    tail_rows: int | None = None,
) -> pd.DataFrame:
    """Volume Profile 컬럼을 최근 봉에 롤링 적용."""
    out = df.copy()
    for k in general_analysis_volume_columns():
        out[ga_col(k)] = 0.0 if k != "vp_in_value_area" else 0

    lb = LOOKBACK_BARS.get(interval, 80)
    n = len(out)
    if n < lb + 1:
        return out
    if tail_rows is None:
        tail_rows = CONTEXT_TAIL_ROWS.get(interval, 5000)
    start = max(lb, n - tail_rows)

    for i in range(start, n):
        snap = general_analysis_volume_snapshot(out.iloc[i - lb : i])
        idx = out.index[i]
        for k, v in snap.items():
            out.at[idx, k] = v

    return out


def general_analysis_apply_harmonic_to_bars(
    df: pd.DataFrame,
    interval: int,
    tail_rows: int | None = None,
) -> pd.DataFrame:
    """하모닉 패턴 컬럼 롤링 적용."""
    out = df.copy()
    for k in general_analysis_harmonic_columns():
        default = "none" if k == "harmonic_label" else 0
        out[ga_col(k)] = default

    lb = LOOKBACK_BARS.get(interval, 80)
    n = len(out)
    if n < lb + 1:
        return out
    if tail_rows is None:
        tail_rows = CONTEXT_TAIL_ROWS.get(interval, 5000)
    start = max(lb, n - tail_rows)

    for i in range(start, n):
        snap = general_analysis_harmonic_snapshot(out.iloc[i - lb : i])
        idx = out.index[i]
        for k, v in snap.items():
            out.at[idx, k] = v

    return out


def general_analysis_apply_context_features(
    df: pd.DataFrame,
    interval: int,
    tail_rows: int | None = None,
) -> pd.DataFrame:
    """
    패턴·파동·VP·하모닉 lookback 라벨을 봉 시계열에 병합.

    Args:
        df: general_analysis_enrich_bars 1단계 결과.
        interval: 분봉 간격(분).
        tail_rows: 롤링 적용 봉 수 상한.

    Returns:
        컨텍스트 ga_* 컬럼이 추가된 DataFrame.
    """
    out = general_analysis_apply_patterns_to_bars(df, interval, tail_rows)
    out = general_analysis_apply_wave_to_bars(out, interval, tail_rows)
    out = general_analysis_apply_volume_to_bars(out, interval, tail_rows)
    out = general_analysis_apply_harmonic_to_bars(out, interval, tail_rows)
    return out
