"""
VYNDR Synergy Service — NBA play-type data.
Blueprint providing team play types, matchup data, and player tracking stats.
Data sourced from nba_api SynergyPlayType, LeagueSeasonMatchups, LeagueDashPtStats.
"""

import time
import logging
from flask import Blueprint, request, jsonify

from utils.data_warehouse import fetch_with_cache
from utils.retry import api_call_with_retry

logger = logging.getLogger('vyndr')
synergy_bp = Blueprint('synergy', __name__)

NBA_API_DELAY = 0.6  # seconds between nba_api calls

PLAY_TYPES = [
    'Transition', 'Isolation', 'PRBallHandler', 'PRRollman',
    'Postup', 'Spotup', 'Handoff', 'Cut', 'OffScreen',
    'OffRebound', 'Misc'
]


def _nba_api_delay():
    """Enforce 0.6s delay between all nba_api calls."""
    time.sleep(NBA_API_DELAY)


@synergy_bp.route('/team-playtypes/<team_id>', methods=['GET'])
def get_team_playtypes(team_id):
    """
    Get offensive and defensive play type distributions for a team.
    Sources: nba_api SynergyPlayType. Cache 6hr.

    Args:
        team_id: NBA team ID.

    Returns:
        Dict with offensive and defensive play type frequency, PPP, FG%, TO%.
    """
    def _fetch():
        _nba_api_delay()
        try:
            from nba_api.stats.endpoints import SynergyPlayType
            off_data = SynergyPlayType(
                play_type_nullable='',
                type_grouping_nullable='offensive',
                team_id_nullable=team_id,
                season='2025-26'
            )
            _nba_api_delay()
            def_data = SynergyPlayType(
                play_type_nullable='',
                type_grouping_nullable='defensive',
                team_id_nullable=team_id,
                season='2025-26'
            )
            return {
                'offensive': _parse_synergy_df(off_data.get_data_frames()[0]),
                'defensive': _parse_synergy_df(def_data.get_data_frames()[0])
            }
        except Exception as e:
            logger.warning(f'[VYNDR] Synergy fetch failed for team {team_id}: {e}')
            return None

    data = fetch_with_cache(
        f'synergy_team_{team_id}',
        _fetch,
        data_type='player_stats',
        has_game_today=False
    )

    if data is None:
        return jsonify({'error': 'Synergy data unavailable', 'team_id': team_id}), 503

    return jsonify({
        'team_id': team_id,
        'play_types': data,
        'play_type_count': len(PLAY_TYPES)
    })


@synergy_bp.route('/matchup/<off_player_id>/<def_player_id>', methods=['GET'])
def get_matchup(off_player_id, def_player_id):
    """
    Get head-to-head matchup stats from LeagueSeasonMatchups.

    Args:
        off_player_id: Offensive player ID.
        def_player_id: Defensive player ID.

    Returns:
        H2H stats or null if insufficient data.
    """
    def _fetch():
        _nba_api_delay()
        try:
            from nba_api.stats.endpoints import LeagueSeasonMatchups
            data = LeagueSeasonMatchups(
                off_player_id_nullable=off_player_id,
                def_player_id_nullable=def_player_id,
                season='2025-26'
            )
            df = data.get_data_frames()[0]
            if df.empty:
                return None
            row = df.iloc[0]
            return {
                'possessions': int(row.get('POSS', 0)),
                'player_pts': float(row.get('PLAYER_PTS', 0)),
                'fg_pct': float(row.get('FG_PCT', 0)),
                'matchup_quality': 'sufficient' if int(row.get('POSS', 0)) >= 20 else 'limited'
            }
        except Exception as e:
            logger.warning(f'[VYNDR] Matchup fetch failed: {e}')
            return None

    data = fetch_with_cache(
        f'matchup_{off_player_id}_{def_player_id}',
        _fetch,
        data_type='player_stats'
    )

    if data is None:
        return jsonify({'matchup': None, 'reason': 'insufficient_data'}), 200

    return jsonify({'matchup': data})


@synergy_bp.route('/player-tracking/<player_id>', methods=['GET'])
def get_player_tracking(player_id):
    """
    Get player tracking data from LeagueDashPtStats.
    Type parameter selects tracking category.

    Args:
        player_id: NBA player ID.
        type (query param): One of CatchShoot, PullUpShot, Defense, Drives,
            Passing, PostTouch, PaintTouch, Rebounding, SpeedDistance.

    Returns:
        Tracking stats for the specified category.
    """
    tracking_type = request.args.get('type', 'Defense')

    def _fetch():
        _nba_api_delay()
        try:
            from nba_api.stats.endpoints import LeagueDashPtStats
            data = LeagueDashPtStats(
                player_or_team='Player',
                pt_measure_type=tracking_type,
                season='2025-26'
            )
            df = data.get_data_frames()[0]
            player_row = df[df['PLAYER_ID'] == int(player_id)]
            if player_row.empty:
                return None
            return player_row.iloc[0].to_dict()
        except Exception as e:
            logger.warning(f'[VYNDR] Tracking fetch failed for {player_id}: {e}')
            return None

    data = fetch_with_cache(
        f'tracking_{player_id}_{tracking_type}',
        _fetch,
        data_type='player_stats'
    )

    if data is None:
        return jsonify({'tracking': None, 'type': tracking_type}), 200

    return jsonify({'player_id': player_id, 'type': tracking_type, 'tracking': data})


@synergy_bp.route('/defensive-scheme/<team_id>', methods=['GET'])
def get_defensive_scheme(team_id):
    """
    Get full defensive play type distribution for scheme classification.
    Returns distribution that schemeClassifier.js consumes.

    Args:
        team_id: NBA team ID.

    Returns:
        Defensive play type frequency distribution.
    """
    def _fetch():
        _nba_api_delay()
        try:
            from nba_api.stats.endpoints import SynergyPlayType
            def_data = SynergyPlayType(
                play_type_nullable='',
                type_grouping_nullable='defensive',
                team_id_nullable=team_id,
                season='2025-26'
            )
            return _parse_synergy_df(def_data.get_data_frames()[0])
        except Exception as e:
            logger.warning(f'[VYNDR] Defensive scheme fetch failed: {e}')
            return None

    data = fetch_with_cache(
        f'defense_scheme_{team_id}',
        _fetch,
        data_type='player_stats',
        has_game_today=True
    )

    if data is None:
        return jsonify({'scheme': None, 'reason': 'synergy_unavailable'}), 200

    return jsonify({'team_id': team_id, 'defensive_distribution': data})


def _parse_synergy_df(df):
    """Parse Synergy DataFrame into play type distribution dict."""
    if df is None or df.empty:
        return {}
    result = {}
    for _, row in df.iterrows():
        play_type = row.get('PLAY_TYPE', 'Unknown')
        result[play_type] = {
            'frequency_pct': float(row.get('POSS_PCT', 0)),
            'ppp': float(row.get('PPP', 0)),
            'fg_pct': float(row.get('FG_PCT', 0)),
            'to_pct': float(row.get('TOV_PCT', 0))
        }
    return result
