"""
VYNDR Capper Content Formatter
Pre-formatted post text for manual social posting.
Breaking alerts, daily scans, results recap, miss autopsy.
A- and above ONLY. SHADOW_MODE first 2 weeks.
"""

import logging

logger = logging.getLogger('vyndr')

# Sequential pick counter (loaded from grade_outcomes on boot)
_pick_counter = 0


def get_next_pick_number():
    """Get and increment sequential pick number."""
    global _pick_counter
    _pick_counter += 1
    return _pick_counter


def set_pick_counter(value):
    """Set the pick counter (called on boot from grade_outcomes max)."""
    global _pick_counter
    _pick_counter = value


def format_capper_post(grade_result, sport):
    """
    Generate pre-formatted post text for the capper account.
    Kev copies and posts manually. Automate via X API later.

    Args:
        grade_result: Grade result dict with player, stat_type, grade, etc.
        sport: 'nba' or 'mlb'.

    Returns:
        Formatted post string.
    """
    emoji = '\U0001f3c0' if sport == 'nba' else '\u26be\ufe0f'
    pick_num = get_next_pick_number()

    if grade_result.get('trigger') == 'beat_reporter_scratch':
        return (
            f"BREAKING: {grade_result['scratched_player']} scratched.\n\n"
            f"{grade_result['player']} {grade_result['stat_type'].upper()} "
            f"{grade_result['over_under'].upper()} {grade_result['line']} "
            f"moved from {grade_result['old_grade']} to {grade_result['grade']}.\n\n"
            f"Engine projection: {grade_result['projected_value']} | "
            f"Edge: {grade_result.get('real_edge', {}).get('real_edge', 0):.1%}\n\n"
            f"\U0001f512 {pick_num:03d}"
        )

    return (
        f"{emoji} VYNDR Scan\n\n"
        f"{grade_result.get('player', 'Unknown')} "
        f"{grade_result.get('over_under', 'over').upper()} "
        f"{grade_result.get('line', '?')} {grade_result.get('stat_type', '')} "
        f"\u2192 Grade: {grade_result.get('grade', '?')}\n\n"
        f"Projection: {grade_result.get('projected_value', '?')} | "
        f"Line: {grade_result.get('line', '?')} | "
        f"Edge: {grade_result.get('real_edge', {}).get('real_edge', 0):.1%}\n\n"
        f"\U0001f512 {pick_num:03d}"
    )


def format_daily_results(resolved_grades, game_date):
    """
    Format yesterday's results for morning recap post.

    Args:
        resolved_grades: List of resolved grade dicts.
        game_date: Date string for the header.

    Returns:
        Formatted results recap string.
    """
    if not resolved_grades:
        return f"\U0001f4ca No graded plays for {game_date}."

    lines = [f"\U0001f4ca Yesterday's VYNDR Grades:\n"]

    for g in resolved_grades:
        icon = '\u2705' if g.get('hit') else '\u274c'
        pick_num = g.get('pick_number', 0)
        lines.append(
            f"{icon} \U0001f512 {pick_num:03d} \u2014 {g.get('player_name', '?')} "
            f"{g.get('over_under', '').upper()} {g.get('prop_line', '?')} "
            f"{g.get('stat_type', '')} "
            f"\u2192 {g.get('grade', '?')} \u2192 "
            f"{'HIT' if g.get('hit') else 'MISS'} "
            f"({g.get('actual_value', '?')})"
        )

    total = len(resolved_grades)
    hit_count = sum(1 for g in resolved_grades if g.get('hit'))
    pct = round(hit_count / total * 100) if total > 0 else 0
    lines.append(
        f"\nRunning record: {hit_count}-{total - hit_count} "
        f"({pct}%) on graded plays"
    )

    return '\n'.join(lines)


def format_miss_autopsy(resolved_grade):
    """
    When an A-grade pick misses, explain WHY.
    Transparency builds trust more than wins alone.

    Args:
        resolved_grade: Resolved grade dict with game_context.

    Returns:
        Formatted miss autopsy string.
    """
    context = resolved_grade.get('game_context', {})
    reasons = []

    if context.get('player_injured_during_game'):
        reasons.append(
            f"Left game with {context.get('injury_type', 'injury')} \u2014 "
            f"played {context.get('actual_minutes', '?')} of projected "
            f"{context.get('projected_minutes', '?')} minutes"
        )
    if context.get('blowout'):
        pulled_q = '3rd' if context.get('pulled_quarter') == 3 else '4th'
        reasons.append(f"Blowout \u2014 pulled in {pulled_q} quarter")
    if context.get('foul_trouble'):
        reasons.append(
            f"Foul trouble \u2014 {context.get('fouls', '?')} fouls, "
            f"sat extended minutes"
        )
    if context.get('ejection'):
        reasons.append("Ejected from game")
    if not reasons:
        reasons.append(
            "Model miss \u2014 no external factor identified. "
            "Logged for calibration."
        )

    pick_num = resolved_grade.get('pick_number', 0)
    return (
        f"\U0001f4cb Miss Autopsy \u2014 \U0001f512 {pick_num:03d}\n\n"
        f"{resolved_grade.get('player_name', '?')} "
        f"{resolved_grade.get('over_under', '').upper()} "
        f"{resolved_grade.get('prop_line', '?')} {resolved_grade.get('stat_type', '')}\n"
        f"Grade: {resolved_grade.get('grade', '?')} | "
        f"Projected: {resolved_grade.get('projected_value', '?')} | "
        f"Actual: {resolved_grade.get('actual_value', '?')}\n\n"
        f"Why: {'. '.join(reasons)}"
    )
