"""Volatility Signature Plot pipeline functions.

Pipeline functions:
    vol_signature_analyzer - Real-time volatility signature analysis
"""

from __future__ import annotations

from typing import Any, Callable

from horizon._horizon import (
    noise_variance_estimate,
    optimal_sampling_frequency,
    two_scale_realized_vol,
    volatility_signature,
)
from horizon.context import Context


def vol_signature_analyzer(
    feed: str,
    window: int = 500,
    recompute_interval: int = 100,
) -> Callable[[Context], dict[str, Any]]:
    """Create a volatility signature analysis pipeline function.

    Collects prices and periodically computes the volatility signature
    plot to detect optimal sampling frequency and microstructure noise.

    Args:
        feed: Feed name to read price data from.
        window: Number of prices to collect before analysis.
        recompute_interval: Recompute every N ticks.

    Returns:
        Pipeline function: (Context) -> dict with keys:
            tsrv, noise_variance, optimal_frequency, n_prices
    """
    from horizon._horizon import auth_require_pro
    auth_require_pro()

    price_histories: dict[str, list[float]] = {}
    tick_counts: dict[str, int] = {}
    cached_results: dict[str, dict[str, Any]] = {}

    def _vol_signature_analyzer(ctx: Context) -> dict[str, Any]:
        market_id = ctx.market.id if ctx.market else "__default__"
        fd = ctx.feeds.get(feed)

        if market_id not in price_histories:
            price_histories[market_id] = []
            tick_counts[market_id] = 0
            cached_results[market_id] = {
                "tsrv": 0.0,
                "noise_variance": 0.0,
                "optimal_frequency": 1,
                "n_prices": 0,
            }

        prices = price_histories[market_id]

        if fd is not None and fd.price > 0:
            prices.append(fd.price)
            if len(prices) > window * 2:
                prices[:] = prices[-window:]

        tick_counts[market_id] += 1

        if (
            len(prices) >= 20
            and tick_counts[market_id] % recompute_interval == 0
        ):
            try:
                sig = volatility_signature(prices)
                cached_results[market_id] = {
                    "tsrv": sig.two_scale_rv,
                    "noise_variance": sig.noise_variance,
                    "optimal_frequency": sig.optimal_frequency,
                    "n_prices": len(prices),
                }
            except (ValueError, RuntimeError):
                pass

        result = cached_results[market_id].copy()
        result["n_prices"] = len(prices)
        return result

    _vol_signature_analyzer.__name__ = "vol_signature_analyzer"
    return _vol_signature_analyzer
