"""
Tier 2: Market / sportsbook sanity validation.

Cross-checks internal player-team mappings against market data.
Uses SGO API player props to confirm market presence.
"""

import logging
from typing import List, Dict, Any

import psycopg2.extras

from .normalization import normalize_player_name, normalize_team_abbrev
from .enums import SourceTier

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


def ingest_market_props(conn, league: str, run_id: str) -> List[Dict[str, Any]]:
    """
    Read rm_forecast_precomputed for PLAYER_PROP entries.
    These represent props that sportsbooks are actively offering.
    """
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cur.execute("""
        SELECT event_id, player_name, league, team_id, status,
               created_at
        FROM rm_forecast_precomputed
        WHERE LOWER(league) = LOWER(%s)
          AND forecast_type = 'PLAYER_PROP'
          AND date_et = (NOW() AT TIME ZONE 'America/New_York')::date
    """, (league,))

    rows = cur.fetchall()
    cur.close()

    results = []
    for row in rows:
        results.append({
            "event_id": row["event_id"],
            "player_name": row["player_name"],
            "normalized_name": normalize_player_name(row["player_name"] or ""),
            "team": normalize_team_abbrev(row.get("team_id", "") or ""),
            "league": league,
            "prop_type": "",
            "market_status": row.get("status", "ACTIVE"),
            "source": "rm_forecast_precomputed",
            "source_tier": SourceTier.MARKET,
            "run_id": run_id,
        })

    log.info(f"[market] Ingested {len(results)} market props for {league}")
    return results


def ingest_market_from_sgo_odds(conn, league: str, run_id: str) -> List[Dict[str, Any]]:
    """
    Read player prop data from rm_events.prop_count and rm_team_props_cache.
    This tells us which players the sportsbooks are actively pricing.
    """
    cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
    cur.execute("""
        SELECT event_id, team, team_name, team_short, league, props_data, created_at
        FROM rm_team_props_cache
        WHERE LOWER(league) = LOWER(%s)
          AND DATE(created_at AT TIME ZONE 'America/New_York')
              = (NOW() AT TIME ZONE 'America/New_York')::date
    """, (league,))

    rows = cur.fetchall()
    cur.close()

    results = []
    for row in rows:
        props_data = row.get("props_data") or {}
        players = props_data.get("players", [])
        if isinstance(players, list):
            for p in players:
                pname = p.get("playerName", "") or p.get("player", "")
                if pname:
                    results.append({
                        "event_id": row["event_id"],
                        "player_name": pname,
                        "normalized_name": normalize_player_name(pname),
                        "team": normalize_team_abbrev(row.get("team", "") or ""),
                        "league": league,
                        "source": "rm_team_props_cache",
                        "source_tier": SourceTier.MARKET,
                        "run_id": run_id,
                    })

    log.info(f"[market] Ingested {len(results)} market-confirmed players from team props for {league}")
    return results


def check_market_presence(market_props: List[Dict[str, Any]], player_name: str) -> bool:
    """Check if a player has an active market across any sportsbook data."""
    norm = normalize_player_name(player_name)
    for mp in market_props:
        if mp.get("normalized_name") == norm:
            return True
    return False
