"""Shared test fixtures."""

from unittest.mock import MagicMock, patch

import pandas as pd
import pytest

from dyfinance._cache import CacheEngine


# ---------------------------------------------------------------------------
# Shared fixtures
# ---------------------------------------------------------------------------

@pytest.fixture(autouse=True)
def _isolate_cache(tmp_path):
    """Ensure each test uses its own DuckDB cache."""
    CacheEngine.reset_default(tmp_path / "test.duckdb")
    yield
    if CacheEngine._default_instance is not None:
        CacheEngine._default_instance.close()
        CacheEngine._default_instance = None


@pytest.fixture
def mock_yf_ticker():
    """Patch yfinance.Ticker and yield the configured mock instance.

    Usage::

        def test_something(self, mock_yf_ticker):
            mock_yf_ticker.history.return_value = make_raw_df()
            t = Ticker("AAPL")
            ...
    """
    with patch("dyfinance._ticker.yfinance.Ticker") as MockYfTicker:
        mock_instance = MagicMock()
        mock_instance.ticker = "AAPL"
        MockYfTicker.return_value = mock_instance
        yield mock_instance


@pytest.fixture
def tmp_cache(tmp_path):
    """Create a temporary DuckDB cache for testing."""
    db_path = tmp_path / "test_cache.duckdb"
    engine = CacheEngine(db_path)
    yield engine
    engine.close()


@pytest.fixture
def sample_ohlcv_df():
    """A minimal yfinance-like OHLCV DataFrame (raw, unadjusted)."""
    dates = pd.date_range("2024-01-02", periods=5, freq="B", tz="America/New_York")
    return pd.DataFrame(
        {
            "Open": [100.0, 101.0, 102.0, 103.0, 104.0],
            "High": [101.0, 102.0, 103.0, 104.0, 105.0],
            "Low": [99.0, 100.0, 101.0, 102.0, 103.0],
            "Close": [100.5, 101.5, 102.5, 103.5, 104.5],
            "Adj Close": [100.5, 101.5, 102.5, 103.5, 104.5],
            "Volume": [1000000, 1100000, 1200000, 1300000, 1400000],
            "Dividends": [0.0, 0.0, 0.5, 0.0, 0.0],
            "Stock Splits": [0.0, 0.0, 0.0, 0.0, 0.0],
            "Capital Gains": [0.0, 0.0, 0.0, 0.0, 0.0],
        },
        index=dates,
    )


@pytest.fixture
def sample_ohlcv_df_extended():
    """Extended OHLCV DataFrame covering Jan-Mar 2024."""
    dates = pd.date_range("2024-01-02", periods=60, freq="B", tz="America/New_York")
    n = len(dates)
    return pd.DataFrame(
        {
            "Open": [100.0 + i * 0.5 for i in range(n)],
            "High": [101.0 + i * 0.5 for i in range(n)],
            "Low": [99.0 + i * 0.5 for i in range(n)],
            "Close": [100.5 + i * 0.5 for i in range(n)],
            "Adj Close": [100.5 + i * 0.5 for i in range(n)],
            "Volume": [1000000 + i * 10000 for i in range(n)],
            "Dividends": [0.0] * n,
            "Stock Splits": [0.0] * n,
            "Capital Gains": [0.0] * n,
        },
        index=dates,
    )
