"""Backfill and cache population configuration.

Centralizes all backfill operational constants: Vision probe caching, chunk
sizing, trailing-edge guards, memory limits, and daemon tuning.

All values load from environment variables (OPENDEVIATIONBAR_BACKFILL_ prefix).
"""

from __future__ import annotations

from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class BackfillConfig(BaseSettings):
    """Backfill operational configuration.

    Environment Variables
    ---------------------
    OPENDEVIATIONBAR_BACKFILL_VISION_PROBE_TTL_S : int
        Redis cache TTL for 404'd Vision dates (default: 3600 = 1h)
    OPENDEVIATIONBAR_BACKFILL_MAX_PAIRS_PER_ITERATION : int
        Memory-bounded pair loop: max symbol/threshold pairs per iteration (default: 40)
    OPENDEVIATIONBAR_BACKFILL_LOOP_INTERVAL_S : int
        Daemon polling interval between iterations (default: 300 = 5min)
    OPENDEVIATIONBAR_BACKFILL_CHUNK_DURATION_MS : int
        Ariadne chunk size for chunked gap-fill (default: 86400000 = 1 day)
    OPENDEVIATIONBAR_BACKFILL_SUSTAINED_FAILURE_THRESHOLD : int
        Consecutive errors before Telegram alert (default: 5)
    OPENDEVIATIONBAR_BACKFILL_TRAILING_EDGE_MIN_GAP_S : int
        Minimum gap age before trailing-edge fill; prevents sidecar overlap (default: 1800 = 30min)
    OPENDEVIATIONBAR_BACKFILL_FLUSH_THRESHOLD : int
        Bounded flush: bars accumulated before CH write in populate (default: 10000)
    OPENDEVIATIONBAR_MEMORY_MAX_BYTES : int
        Soft memory ceiling for watermark checks (default: 4294967296 = 4GB).
        Also accepted as OPENDEVIATIONBAR_BACKFILL_MEMORY_MAX_BYTES.
        Set in .service files to match systemd MemoryMax (kintsugi: 20GB, sidecar: 2.5GB).
    OPENDEVIATIONBAR_BACKFILL_PAGINATED_MAX_TRADES : int
        Server-side gap-fill pagination hard cap (default: 100000)
    OPENDEVIATIONBAR_BACKFILL_MIN_PARQUET_VALIDATE : int
        Minimum Parquet file size for integrity validation (default: 12 bytes)
    OPENDEVIATIONBAR_BACKFILL_MIN_PARQUET_CACHE : int
        Minimum Parquet file size for cache reads (default: 1024 bytes)
    """

    model_config = SettingsConfigDict(
        env_prefix="OPENDEVIATIONBAR_BACKFILL_",
        case_sensitive=False,
    )

    # Redis cache TTL for 404'd Vision dates (seconds)
    vision_probe_ttl_s: int = 3600  # 1 hour

    # Shorter TTL for dates within 2 days of today — Vision archives for
    # recent dates may not yet be published; re-probe sooner (PYEF-02).
    vision_probe_ttl_recent_s: int = 900  # 15 minutes

    # Memory-bounded pair loop: max symbol/threshold pairs per iteration
    max_pairs_per_iteration: int = 40

    # Daemon polling interval between iterations (seconds)
    loop_interval_s: int = 300  # 5 minutes

    # Ariadne chunk size for chunked gap-fill (milliseconds)
    chunk_duration_ms: int = 1 * 24 * 60 * 60 * 1000  # 1 day

    # Consecutive errors before sending Telegram sustained-failure alert
    sustained_failure_threshold: int = 5

    # Minimum gap age (seconds) before trailing-edge fill. Prevents overlap
    # with sidecar which is actively writing the trailing edge.
    trailing_edge_min_gap_s: int = 1800  # 30 minutes

    # Bounded flush: bars accumulated before ClickHouse write in populate
    flush_threshold: int = Field(
        10_000,
        validation_alias=AliasChoices(
            "OPENDEVIATIONBAR_FLUSH_THRESHOLD",
            "OPENDEVIATIONBAR_BACKFILL_FLUSH_THRESHOLD",
        ),
    )

    # Soft memory ceiling for watermark checks (bytes).
    # Set via OPENDEVIATIONBAR_MEMORY_MAX_BYTES in service files to match systemd MemoryMax.
    # Watermark tiers: gc at 65%, abort at 90% — both fire before systemd hard kill.
    # AliasChoices: accepts the shorter MEMORY_MAX_BYTES name set in .service files
    # (same pattern as flush_threshold above), with BACKFILL_ prefix as alternative.
    memory_max_bytes: int = Field(
        4 * 1024**3,  # 4 GB default; overridden by service files
        validation_alias=AliasChoices(
            "OPENDEVIATIONBAR_MEMORY_MAX_BYTES",
            "OPENDEVIATIONBAR_BACKFILL_MEMORY_MAX_BYTES",
        ),
    )

    # Server-side gap-fill pagination hard cap (sidecar API)
    paginated_max_trades: int = 100_000

    # Minimum Parquet file size for integrity validation (bytes)
    min_parquet_validate: int = 12

    # Minimum Parquet file size for cache reads (bytes)
    min_parquet_cache: int = 1024
