from __future__ import annotations

import re
import time
import urllib.error
import urllib.request
from datetime import date
from pathlib import Path

import pandas as pd

from psx_signal.config import DataConfig
from psx_signal.data.artifacts import MarketDataArtifact
from psx_signal.data.normalization import normalize_equities, normalize_indices
from psx_signal.data.providers.base import DataProvider


class PsxProvider(DataProvider):
    """Official-file provider. Network use requires operator-supplied documented/licensed URL template."""

    DATE_PATTERNS = (
        re.compile(r"(?P<y>20\d{2})[-_]?(?P<m>\d{2})[-_]?(?P<d>\d{2})"),
        re.compile(r"(?P<d>\d{2})[-_](?P<m>\d{2})[-_](?P<y>20\d{2})"),
    )

    def __init__(self, config: DataConfig) -> None:
        self.config = config
        self.inbox = Path(config.inbox)

    @classmethod
    def infer_date(cls, path: Path) -> date | None:
        for pattern in cls.DATE_PATTERNS:
            match = pattern.search(path.stem)
            if match:
                try:
                    return date(int(match["y"]), int(match["m"]), int(match["d"]))
                except ValueError:
                    return None
        return None

    @staticmethod
    def infer_kind(path: Path) -> str:
        name = str(path).lower()
        if "corporate" in name or "action" in name or "payout" in name:
            return "corporate_actions"
        if "constituent" in name:
            return "constituents"
        if "index" in name or "kse100" in name:
            return "indices"
        if "metadata" in name or "listing" in name or "companies" in name:
            return "metadata"
        return "equities"

    def available_artifacts(
        self, start: date | None = None, end: date | None = None, kind: str | None = None
    ) -> list[MarketDataArtifact]:
        if not self.inbox.exists():
            return []
        artifacts: list[MarketDataArtifact] = []
        for path in sorted(self.inbox.rglob("*")):
            if not path.is_file() or path.suffix.lower() not in {".csv", ".txt", ".zip"}:
                continue
            inferred_kind = self.infer_kind(path)
            inferred_date = self.infer_date(path)
            if kind and inferred_kind != kind:
                continue
            if start and inferred_date and inferred_date < start:
                continue
            if end and inferred_date and inferred_date > end:
                continue
            artifacts.append(MarketDataArtifact(
                path=path, kind=inferred_kind, source_reference=path.name,
                trading_date=inferred_date, provider="psx",
            ))
        return artifacts

    def fetch_artifact(self, value: date, kind: str = "equities") -> MarketDataArtifact | None:
        matches = [
            artifact for artifact in self.available_artifacts(value, value, kind)
            if artifact.trading_date == value
        ]
        if matches:
            return matches[0]
        template = self.config.licensed_url_template.strip()
        if not template:
            return None
        url = template.format(date=value.isoformat(), compact_date=value.strftime("%Y%m%d"), kind=kind)
        request = urllib.request.Request(url, headers={"User-Agent": self.config.user_agent})
        last_error: Exception | None = None
        for attempt in range(self.config.request_retries):
            try:
                with urllib.request.urlopen(request, timeout=self.config.request_timeout_seconds) as response:
                    content = response.read()
                cache = self.inbox / ".cache" / kind
                cache.mkdir(parents=True, exist_ok=True)
                target = cache / f"{value.isoformat()}.csv"
                temporary = target.with_suffix(".tmp")
                temporary.write_bytes(content)
                temporary.replace(target)
                time.sleep(self.config.rate_limit_seconds)
                return MarketDataArtifact(target, kind, url, value, "psx")
            except urllib.error.HTTPError as exc:
                if exc.code == 404:
                    return None
                last_error = exc
            except (urllib.error.URLError, TimeoutError) as exc:
                last_error = exc
            if attempt + 1 < self.config.request_retries:
                time.sleep(self.config.retry_backoff_seconds * (2**attempt))
        raise RuntimeError(f"Failed to fetch {url}: {last_error}")

    def get_symbols(self) -> list[str]:
        frame = self.get_ohlcv()
        return sorted(frame["symbol"].dropna().unique().tolist()) if not frame.empty else []

    def get_eod(self, value: date) -> pd.DataFrame:
        artifact = self.fetch_artifact(value, "equities")
        if artifact is None:
            return pd.DataFrame()
        frame = normalize_equities(artifact, artifact.source_reference)
        return frame[frame["symbol"] != "KSE100"].reset_index(drop=True)

    def get_ohlcv(
        self, symbols: list[str] | None = None, start: date | None = None, end: date | None = None
    ) -> pd.DataFrame:
        frames = [
            normalize_equities(artifact, artifact.source_reference)
            for artifact in self.available_artifacts(start, end, "equities")
        ]
        if not frames:
            return pd.DataFrame()
        frame = pd.concat(frames, ignore_index=True)
        frame = frame[frame["symbol"] != "KSE100"]
        if symbols:
            frame = frame[frame["symbol"].isin({symbol.upper() for symbol in symbols})]
        if start:
            frame = frame[frame["date"] >= pd.Timestamp(start)]
        if end:
            frame = frame[frame["date"] <= pd.Timestamp(end)]
        return frame.sort_values(["symbol", "date"]).reset_index(drop=True)

    def get_index_history(
        self, symbol: str = "KSE100", start: date | None = None, end: date | None = None
    ) -> pd.DataFrame:
        frames = [
            normalize_indices(artifact, artifact.source_reference, symbol)
            for artifact in self.available_artifacts(start, end, "indices")
        ]
        for artifact in self.available_artifacts(start, end, "equities"):
            equities = normalize_equities(artifact, artifact.source_reference)
            index_rows = equities[equities["symbol"] == symbol.upper()]
            if not index_rows.empty:
                frames.append(index_rows.rename(columns={"symbol": "index"}))
        if not frames:
            return pd.DataFrame()
        frame = pd.concat(frames, ignore_index=True)
        frame = frame[frame["index"] == symbol.upper()]
        if start:
            frame = frame[frame["date"] >= pd.Timestamp(start)]
        if end:
            frame = frame[frame["date"] <= pd.Timestamp(end)]
        return frame.sort_values("date").reset_index(drop=True)
