from __future__ import annotations

from datetime import date
from pathlib import Path

import pandas as pd

from psx_signal.data.providers.base import DataProvider
from psx_signal.data.schema import NUMERIC_COLUMNS, REQUIRED_COLUMNS


class CsvDataProvider(DataProvider):
    """Read immutable CSV snapshots. One combined file or a directory of CSV files is supported."""

    def __init__(self, path: str | Path, benchmark_path: str | Path | None = None) -> None:
        self.path = Path(path)
        self.benchmark_path = Path(benchmark_path) if benchmark_path else None

    @staticmethod
    def _read(path: Path) -> pd.DataFrame:
        files = sorted(path.glob("*.csv")) if path.is_dir() else [path]
        if not files:
            raise FileNotFoundError(f"No CSV files found at {path}")
        frames = [pd.read_csv(file) for file in files]
        frame = pd.concat(frames, ignore_index=True)
        missing = sorted(set(REQUIRED_COLUMNS) - set(frame.columns))
        if missing:
            raise ValueError(f"Missing required columns: {', '.join(missing)}")
        frame["symbol"] = frame["symbol"].astype("string").str.strip().str.upper()
        frame["date"] = pd.to_datetime(frame["date"], errors="raise").dt.normalize()
        for column in set(NUMERIC_COLUMNS).intersection(frame.columns):
            frame[column] = pd.to_numeric(frame[column], errors="coerce")
        if "adjusted_close" not in frame:
            frame["adjusted_close"] = pd.NA
        return frame.sort_values(["symbol", "date"], kind="stable").reset_index(drop=True)

    def get_symbols(self) -> list[str]:
        return sorted(self._read(self.path)["symbol"].dropna().unique().tolist())

    def get_ohlcv(
        self, symbols: list[str] | None = None, start: date | None = None, end: date | None = None
    ) -> pd.DataFrame:
        frame = self._read(self.path)
        if symbols:
            wanted = {symbol.upper() for symbol in symbols}
            frame = frame[frame["symbol"].isin(wanted)]
        if start:
            frame = frame[frame["date"] >= pd.Timestamp(start)]
        if end:
            frame = frame[frame["date"] <= pd.Timestamp(end)]
        return frame.reset_index(drop=True)

    def get_index_history(
        self, symbol: str = "KSE100", start: date | None = None, end: date | None = None
    ) -> pd.DataFrame:
        frame = self._read(self.benchmark_path) if self.benchmark_path else self._read(self.path)
        result = frame[frame["symbol"] == symbol.upper()].copy()
        if result.empty:
            raise ValueError(f"Benchmark symbol {symbol!r} not found")
        if start:
            result = result[result["date"] >= pd.Timestamp(start)]
        if end:
            result = result[result["date"] <= pd.Timestamp(end)]
        return result.reset_index(drop=True)

    def get_sector_information(self) -> pd.DataFrame:
        frame = self._read(self.path)
        if "sector" not in frame:
            return super().get_sector_information()
        return frame[["symbol", "sector"]].dropna().drop_duplicates("symbol").reset_index(drop=True)
