"""SQLite 캔들 로더."""

from __future__ import annotations

import sqlite3
from datetime import datetime, timedelta
from pathlib import Path

import pandas as pd

from deepcoin.data.candle_store import table_name


def load_candles(
    db_path: Path,
    symbol: str,
    interval_min: int,
    lookback_days: int | None = None,
    end_dt: datetime | None = None,
) -> pd.DataFrame:
    """DB에서 캔들 DataFrame을 로드한다.

    Args:
        db_path: SQLite 경로.
        symbol: 코인 심볼.
        interval_min: 분 단위 인터벌.
        lookback_days: 최근 N일만 로드. None이면 전체.
        end_dt: 종료 시각(KST). None이면 DB 최신.

    Returns:
        컬럼: datetime, open, high, low, close, volume (시간 오름차순).
    """
    table = table_name(symbol, interval_min)
    conn = sqlite3.connect(db_path)
    try:
        query = f"""
            SELECT ymdhms, Open, High, Low, Close, Volume
            FROM {table}
            WHERE CODE = ?
            ORDER BY ymdhms ASC
        """
        df = pd.read_sql_query(query, conn, params=(symbol.upper(),))
    except sqlite3.OperationalError as exc:
        raise ValueError(f"테이블 {table} 없음 — 먼저 download_candles.py 실행") from exc
    finally:
        conn.close()

    if df.empty:
        raise ValueError(f"{table} 데이터가 비어 있습니다.")

    df = df.rename(
        columns={
            "ymdhms": "datetime",
            "Open": "open",
            "High": "high",
            "Low": "low",
            "Close": "close",
            "Volume": "volume",
        }
    )
    df["datetime"] = pd.to_datetime(df["datetime"])

    if end_dt is not None:
        df = df[df["datetime"] <= end_dt]

    if lookback_days is not None and not df.empty:
        cutoff = df["datetime"].max() - timedelta(days=lookback_days)
        df = df[df["datetime"] >= cutoff]

    return df.reset_index(drop=True)
