"""Record golden fixtures from live yfinance for offline compatibility testing.

Run manually:
    python -m tests.record_fixtures

Recorded parquet files are committed to the repo and used by test_compat.py.
Rate limit note: Yahoo limits to ~2000 requests/hour.
"""

import json
from pathlib import Path

import pandas as pd
import yfinance as yf

FIXTURES_DIR = Path(__file__).parent / "fixtures"
FIXTURES_DIR.mkdir(exist_ok=True)

# ---------------------------------------------------------------------------
# Ticker.history() fixtures
# ---------------------------------------------------------------------------

HISTORY_FIXTURES = [
    {
        "name": "aapl_1mo_1d_default",
        "ticker": "AAPL",
        "kwargs": {"period": "1mo", "interval": "1d"},
    },
    {
        "name": "aapl_5d_1d_no_actions",
        "ticker": "AAPL",
        "kwargs": {"period": "5d", "interval": "1d", "actions": False},
    },
    {
        "name": "aapl_5d_1d_no_auto_adjust",
        "ticker": "AAPL",
        "kwargs": {"period": "5d", "interval": "1d", "auto_adjust": False},
    },
    {
        "name": "aapl_5d_1d_rounding",
        "ticker": "AAPL",
        "kwargs": {"period": "5d", "interval": "1d", "rounding": True},
    },
    {
        "name": "aapl_5d_1d_back_adjust",
        "ticker": "AAPL",
        "kwargs": {"period": "5d", "interval": "1d", "auto_adjust": False, "back_adjust": True},
    },
    {
        "name": "aapl_5d_1h_intraday",
        "ticker": "AAPL",
        "kwargs": {"period": "5d", "interval": "1h"},
    },
    {
        "name": "aapl_daterange_1d",
        "ticker": "AAPL",
        "kwargs": {"start": "2024-06-01", "end": "2024-06-30", "interval": "1d"},
    },
    {
        "name": "toyota_5d_1d_jpstock",
        "ticker": "7203.T",
        "kwargs": {"period": "5d", "interval": "1d"},
    },
]

# ---------------------------------------------------------------------------
# download() fixtures
# ---------------------------------------------------------------------------

DOWNLOAD_FIXTURES = [
    {
        "name": "dl_aapl_5d_single",
        "kwargs": {"tickers": "AAPL", "period": "5d"},
    },
    {
        "name": "dl_multi_5d_column",
        "kwargs": {"tickers": ["AAPL", "MSFT"], "period": "5d", "group_by": "column"},
    },
    {
        "name": "dl_multi_5d_ticker",
        "kwargs": {"tickers": ["AAPL", "MSFT"], "period": "5d", "group_by": "ticker"},
    },
    {
        "name": "dl_aapl_5d_flat",
        "kwargs": {"tickers": "AAPL", "period": "5d", "multi_level_index": False},
    },
]


def _save_metadata(name: str, fixture_type: str, kwargs: dict, df: pd.DataFrame) -> None:
    """Save fixture metadata as JSON for test verification."""
    meta = {
        "name": name,
        "type": fixture_type,
        "kwargs": {k: str(v) if not isinstance(v, (str, bool, int, float, list)) else v for k, v in kwargs.items()},
        "shape": list(df.shape),
        "columns": list(df.columns) if not isinstance(df.columns, pd.MultiIndex) else [str(c) for c in df.columns],
        "index_name": df.index.name,
        "index_dtype": str(df.index.dtype),
        "dtypes": {str(col): str(dtype) for col, dtype in df.dtypes.items()},
    }
    with open(FIXTURES_DIR / f"{name}.meta.json", "w") as f:
        json.dump(meta, f, indent=2, default=str)


def record_history_fixtures() -> None:
    print("Recording Ticker.history() fixtures...")
    for fixture in HISTORY_FIXTURES:
        name = fixture["name"]
        ticker = fixture["ticker"]
        kwargs = fixture["kwargs"]

        print(f"  {name}: {ticker} {kwargs}")
        t = yf.Ticker(ticker)
        df = t.history(**kwargs)

        if df.empty:
            print(f"    WARNING: Empty DataFrame for {name}, skipping")
            continue

        df.to_parquet(FIXTURES_DIR / f"{name}.parquet")
        _save_metadata(name, "history", {"ticker": ticker, **kwargs}, df)
        print(f"    -> {len(df)} rows, columns: {list(df.columns)}")


def record_download_fixtures() -> None:
    print("\nRecording download() fixtures...")
    for fixture in DOWNLOAD_FIXTURES:
        name = fixture["name"]
        kwargs = fixture["kwargs"]

        print(f"  {name}: {kwargs}")
        df = yf.download(**kwargs)

        if df is None or df.empty:
            print(f"    WARNING: Empty DataFrame for {name}, skipping")
            continue

        df.to_parquet(FIXTURES_DIR / f"{name}.parquet")
        _save_metadata(name, "download", kwargs, df)
        print(f"    -> {len(df)} rows")


if __name__ == "__main__":
    record_history_fixtures()
    record_download_fixtures()
    print("\nDone! Fixtures saved to", FIXTURES_DIR)
