"""Configuration and feature flags for the Publishing Integrity system."""

import os
import json
import logging
from dataclasses import dataclass, field
from typing import Dict, Optional

log = logging.getLogger("pub-integrity")

# ── Database ────────────────────────────────────────────────────────────────
DB_HOST = os.getenv("PI_DB_HOST", "127.0.0.1")
DB_PORT = int(os.getenv("PI_DB_PORT", "5433"))
DB_NAME = os.getenv("PI_DB_NAME", "eventheodds_sports")
DB_USER = os.getenv("PI_DB_USER", "eventheodds")
DB_PASS = os.getenv("PI_DB_PASS", "eventheodds_dev_password")

# ── SGO API ─────────────────────────────────────────────────────────────────
SGO_API_KEY = os.getenv("SPORTSGAMEODDS_API_KEY", "47d6ce020d896ece307a284e8c78ff7f")
SGO_BASE_URL = "https://api.sportsgameodds.com/v2"

# ── Logging ─────────────────────────────────────────────────────────────────
LOG_DIR = os.getenv("PI_LOG_DIR", "/var/log/rainmaker")
LOG_FILE = os.path.join(LOG_DIR, "publishing-integrity.log")

# ── Feature Flags ───────────────────────────────────────────────────────────
# Master switch
PUBLISHING_INTEGRITY_ENABLED = os.getenv("PUBLISHING_INTEGRITY_ENABLED", "true").lower() == "true"

# Per-league flags (default ON for all covered leagues)
LEAGUE_FLAGS: Dict[str, bool] = {
    "nba":    os.getenv("PI_LEAGUE_NBA", "true").lower() == "true",
    "mlb":    os.getenv("PI_LEAGUE_MLB", "true").lower() == "true",
    "nhl":    os.getenv("PI_LEAGUE_NHL", "true").lower() == "true",
    "mls":    os.getenv("PI_LEAGUE_MLS", "true").lower() == "true",
    "epl":    os.getenv("PI_LEAGUE_EPL", "true").lower() == "true",
    "ncaab":  os.getenv("PI_LEAGUE_NCAAB", "true").lower() == "true",
    "la_liga":    os.getenv("PI_LEAGUE_LA_LIGA", "true").lower() == "true",
    "bundesliga": os.getenv("PI_LEAGUE_BUNDESLIGA", "true").lower() == "true",
    "serie_a":    os.getenv("PI_LEAGUE_SERIE_A", "true").lower() == "true",
    "ligue_1":    os.getenv("PI_LEAGUE_LIGUE_1", "true").lower() == "true",
}

# Validation strictness flags
REQUIRE_MARKET_CONFIRMATION = os.getenv("PI_REQUIRE_MARKET_CONFIRMATION", "false").lower() == "true"
REQUIRE_CONFIRMED_LINEUPS = os.getenv("PI_REQUIRE_CONFIRMED_LINEUPS", "false").lower() == "true"

def is_league_enabled(league: str) -> bool:
    if not PUBLISHING_INTEGRITY_ENABLED:
        return False
    return LEAGUE_FLAGS.get(league.lower(), False)


# ── League Validation Policies ──────────────────────────────────────────────

@dataclass
class LeagueValidationPolicy:
    league: str
    # Whether starter-dependent props require confirmed starter
    require_confirmed_starter_for_props: bool = True
    # Whether market presence is required to publish
    require_market_presence: bool = False
    # Max age (minutes) before roster data is considered stale
    roster_freshness_max_min: int = 720       # 12 hours
    # Max age (minutes) before availability data is stale
    availability_freshness_max_min: int = 180  # 3 hours
    # Max age (minutes) before lineup data is stale
    lineup_freshness_max_min: int = 120        # 2 hours
    # Statuses that block publication
    blocking_statuses: list = field(default_factory=lambda: ["OUT", "INACTIVE", "SUSPENDED", "SCRATCHED"])
    # Statuses that allow provisional display (not blocking)
    provisional_statuses: list = field(default_factory=lambda: ["QUESTIONABLE", "PROBABLE"])
    # Minutes before game start when lineup must be confirmed
    lineup_lock_before_game_min: int = 60
    # Whether lineup-dependent props can publish before lineup confirmation
    allow_pre_lineup_props: bool = True
    # Description for admin display
    description: str = ""


# Pre-built league policies
NBA_POLICY = LeagueValidationPolicy(
    league="nba",
    require_confirmed_starter_for_props=False,  # NBA starters often unknown until ~30min before
    require_market_presence=False,
    roster_freshness_max_min=720,
    availability_freshness_max_min=120,
    lineup_freshness_max_min=60,
    lineup_lock_before_game_min=30,
    allow_pre_lineup_props=True,
    description="NBA: availability reported by team, lineups near tipoff"
)

MLB_POLICY = LeagueValidationPolicy(
    league="mlb",
    require_confirmed_starter_for_props=True,   # MLB lineup is critical
    require_market_presence=False,
    roster_freshness_max_min=720,
    availability_freshness_max_min=180,
    lineup_freshness_max_min=90,
    lineup_lock_before_game_min=60,
    allow_pre_lineup_props=False,               # Don't publish MLB props without confirmed lineup
    description="MLB: official lineup required for lineup-dependent props"
)

NHL_POLICY = LeagueValidationPolicy(
    league="nhl",
    require_confirmed_starter_for_props=True,   # Goalie matters heavily
    require_market_presence=False,
    roster_freshness_max_min=720,
    availability_freshness_max_min=180,
    lineup_freshness_max_min=120,
    lineup_lock_before_game_min=60,
    allow_pre_lineup_props=True,                # Non-goalie props OK pre-lineup
    description="NHL: goalie confirmation critical, late scratches common"
)

SOCCER_POLICY = LeagueValidationPolicy(
    league="soccer",
    require_confirmed_starter_for_props=True,
    require_market_presence=False,
    roster_freshness_max_min=1440,             # 24 hours — transfers can be slow
    availability_freshness_max_min=360,
    lineup_freshness_max_min=120,
    lineup_lock_before_game_min=60,
    allow_pre_lineup_props=True,
    description="Soccer: Starting XI confirmed ~1h before kickoff"
)

NCAAM_POLICY = LeagueValidationPolicy(
    league="ncaab",
    require_confirmed_starter_for_props=False,  # NCAA availability reporting is spotty
    require_market_presence=False,
    roster_freshness_max_min=1440,             # 24 hours
    availability_freshness_max_min=360,        # 6 hours — conservative
    lineup_freshness_max_min=120,
    lineup_lock_before_game_min=60,
    allow_pre_lineup_props=True,
    description="NCAAB: conservative — availability varies by conference"
)

MLS_POLICY = LeagueValidationPolicy(
    league="mls",
    require_confirmed_starter_for_props=True,
    require_market_presence=False,
    roster_freshness_max_min=1440,
    availability_freshness_max_min=360,
    lineup_freshness_max_min=120,
    lineup_lock_before_game_min=60,
    allow_pre_lineup_props=True,
    description="MLS: Starting XI near kickoff"
)

POLICY_MAP: Dict[str, LeagueValidationPolicy] = {
    "nba": NBA_POLICY,
    "mlb": MLB_POLICY,
    "nhl": NHL_POLICY,
    "mls": MLS_POLICY,
    "epl": SOCCER_POLICY,
    "la_liga": SOCCER_POLICY,
    "bundesliga": SOCCER_POLICY,
    "serie_a": SOCCER_POLICY,
    "ligue_1": SOCCER_POLICY,
    "ncaab": NCAAM_POLICY,
}

DEFAULT_POLICY = LeagueValidationPolicy(
    league="default",
    require_confirmed_starter_for_props=False,
    require_market_presence=False,
    description="Default conservative policy"
)


def get_policy(league: str) -> LeagueValidationPolicy:
    return POLICY_MAP.get(league.lower(), DEFAULT_POLICY)
