"""BLAW 201 Jeopardy — one-room realtime multiplayer classroom server."""
import asyncio
import copy
import hmac
import io
import json
import os
import secrets
import uuid
from pathlib import Path
from typing import Any

import qrcode
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
from fastapi.responses import Response
from fastapi.staticfiles import StaticFiles

HERE = Path(__file__).resolve().parent
QUESTIONS = json.loads((HERE / 'questions.json').read_text(encoding='utf-8'))
BY_ID = {q['id']: q for q in QUESTIONS}
PIN = os.environ.get('INSTRUCTOR_PIN', '246810')
ROOM = f'{secrets.randbelow(900000)+100000}'

app = FastAPI(title='BLAW 201 Jeopardy')
clients: dict[WebSocket, dict[str, Any]] = {}
players: dict[str, dict[str, Any]] = {}
lock = asyncio.Lock()

def initial_game():
    return {
        'round': 1, 'phase': 'board', 'current': None, 'used': [],
        'winner': None, 'locked_teams': [],
        'teams': [{'id':f't{i}', 'name':f'Team {i}', 'score':0} for i in range(1,5)],
        'final_wagers': {}, 'final_graded': {},
    }

game = initial_game()
history = []


def team_by_id(tid):
    return next((t for t in game['teams'] if t['id']==tid), None)

def snapshot():
    history.append(copy.deepcopy(game))
    if len(history)>50:
        history.pop(0)

def public_state():
    current = BY_ID.get(game['current']) if game['current'] else None
    board = []
    for rd in (1,2):
        categories = []
        for category in dict.fromkeys(q['category'] for q in QUESTIONS if q['round']==rd):
            tiles = [{'id':q['id'], 'value':q['value'], 'used':q['id'] in game['used']}
                     for q in QUESTIONS if q['round']==rd and q['category']==category]
            categories.append({'name': category, 'tiles':tiles})
        board.append({'round':rd,'name':'JEOPARDY' if rd==1 else 'DOUBLE JEOPARDY', 'categories':categories})
    show_question = current and game['phase'] not in ('final_wager',)
    return {
        'room':ROOM, 'round':game['round'], 'phase':game['phase'],
        'current':({'id':current['id'],'category':current['category'],
                    'value':current['value'],'question':current['question']}
                   if show_question else None),
        'board':board, 'teams':copy.deepcopy(game['teams']),
        'winner':copy.deepcopy(game['winner']), 'locked_teams':game['locked_teams'][:],
        'used':game['used'][:],
        'final_graded':copy.deepcopy(game['final_graded']),
    }

async def send_state(ws:WebSocket):
    session=clients.get(ws)
    if not session: return
    state=public_state()
    state['role']=session['role']
    if session['role']=='instructor':
        state['players']=[dict(id=p['id'],name=p['name'],team=p['team'],online=p['online'])
                          for p in players.values()]
        state['history_available']=bool(history)
        state['final_wagers']=copy.deepcopy(game['final_wagers'])
    elif session['role']=='student':
        pid=session['player_id'];player=players.get(pid)
        state['self']={'id':pid,'name':player['name'],'team':player['team']}
        state['eligible']=(game['phase']=='buzz' and player['team'] not in game['locked_teams'])
    await ws.send_json({'type':'state','data':state})

async def broadcast():
    stale=[]
    for ws in list(clients):
        try:
            await send_state(ws)
        except Exception:
            stale.append(ws)
    for ws in stale:
        clients.pop(ws,None)


def process_admin(m):
    typ=m.get('type')
    if typ=='select':
        q=BY_ID.get(m.get('id'))
        if not q or q['round']!=game['round'] or q['id'] in game['used'] or game['phase'] not in ('board','question'):
            raise ValueError('That question cannot be selected right now.')
        snapshot()
        game.update(phase='question',current=q['id'],winner=None,locked_teams=[])
    elif typ=='open_buzz':
        if game['phase']!='question': raise ValueError('Select a question first.')
        snapshot();game['phase']='buzz'
    elif typ=='pause_buzz':
        if game['phase']!='buzz':raise ValueError('Buzzers are not open.')
        snapshot();game['phase']='question'
    elif typ=='judge':
        if game['phase']!='locked' or not game['winner']:raise ValueError('No answer awaits judgment.')
        q=BY_ID[game['current']];tid=game['winner']['team']
        snapshot()
        if m.get('correct') is True:
            team_by_id(tid)['score']+=q['value']
            game['used'].append(q['id'])
            game.update(phase='board', current=None, winner=None, locked_teams=[])
        else:
            team_by_id(tid)['score']-=q['value']
            if tid not in game['locked_teams']:game['locked_teams'].append(tid)
            game.update(phase='buzz',winner=None)
            if len(game['locked_teams'])>=len(game['teams']):
                game['used'].append(q['id']);game.update(phase='board',current=None,winner=None,locked_teams=[])
    elif typ=='skip':
        if game['phase'] not in ('question','buzz','locked'):raise ValueError('No active question.')
        snapshot()
        if game['current'] not in game['used']:game['used'].append(game['current'])
        game.update(phase='board',current=None,winner=None,locked_teams=[])
    elif typ=='round':
        r=int(m.get('value',0))
        if r not in (1,2):raise ValueError('Invalid round.')
        snapshot();game.update(round=r,phase='board',current=None,winner=None,locked_teams=[])
    elif typ=='score':
        team=team_by_id(m.get('team'))
        try:delta=int(m.get('delta'))
        except (ValueError,TypeError):raise ValueError('Enter a numeric score adjustment.')
        if not team or abs(delta)>5000:raise ValueError('Invalid score adjustment.')
        snapshot();team['score']+=delta
    elif typ=='rename':
        team=team_by_id(m.get('team'));name=str(m.get('name','')).strip()[:28]
        if not team or not name:raise ValueError('Enter a team name.')
        snapshot();team['name']=name
    elif typ=='move_player':
        player=players.get(m.get('id'));tid=m.get('team')
        if not player or not team_by_id(tid):raise ValueError('Unknown student or team.')
        player['team']=tid
    elif typ=='undo':
        if not history:raise ValueError('Nothing to undo.')
        previous=history.pop();game.clear();game.update(previous)
    elif typ=='reset':
        if m.get('confirm')!='RESET':raise ValueError('Reset was not confirmed.')
        history.clear();game.clear();game.update(initial_game())
        # Retain students and map to default teams.
        for p in players.values():
            if not team_by_id(p['team']):p['team']='t1'
    elif typ=='final_start':
        snapshot()
        game.update(round=3,phase='final_wager',current='final',winner=None,locked_teams=[],
                    final_wagers={t['id']:0 for t in game['teams']},final_graded={})
    elif typ=='final_wager':
        if game['phase']!='final_wager':raise ValueError('Wagers must be entered before the final question.')
        t=team_by_id(m.get('team'))
        try:wager=int(m.get('wager'))
        except (TypeError, ValueError):raise ValueError('Enter a whole-number wager.')
        cap=max(1000,t['score']) if t else 0
        if not t or wager<0 or wager>cap:raise ValueError(f'Wager must be between $0 and ${cap:,}.')
        snapshot();game['final_wagers'][t['id']]=wager
    elif typ=='final_reveal':
        if game['phase']!='final_wager':raise ValueError('Enter wagers before revealing Final Jeopardy.')
        snapshot();game['phase']='final'
    elif typ=='final_grade':
        if game['phase']!='final':raise ValueError('Final Jeopardy is not active.')
        t=team_by_id(m.get('team'))
        if not t or t['id'] in game['final_graded']:raise ValueError('Team has already been graded.')
        if not isinstance(m.get('correct'),bool):raise ValueError('Select correct or incorrect.')
        snapshot()
        t['score']+=game['final_wagers'].get(t['id'],0)*(1 if m['correct'] else -1)
        game['final_graded'][t['id']]='correct' if m['correct'] else 'incorrect'
    elif typ=='final_finish':
        if game['phase']!='final':raise ValueError('Final Jeopardy is not active.')
        snapshot();game.update(phase='finished',current=None)
    else:
        raise ValueError('Unknown instructor command.')


@app.websocket('/ws')
async def websocket_handler(ws: WebSocket):
    await ws.accept()
    role=None;pid=None
    try:
        raw=await ws.receive_json()
        if raw.get('type')!='hello':
            await ws.send_json({'type':'error','message':'Join first.'});return
        role=raw.get('role')
        if role not in ('student','display','instructor'):
            await ws.send_json({'type':'error','message':'Unknown role.'});return
        if role=='instructor' and not hmac.compare_digest(str(raw.get('pin','')),PIN):
            await ws.send_json({'type':'error','message':'Incorrect instructor PIN.'});return
        if role=='student':
            if str(raw.get('room','')).strip()!=ROOM:
                await ws.send_json({'type':'error','message':'Incorrect class code. Scan the projector QR code.'});return
            name=str(raw.get('name','')).strip()[:40]
            team=raw.get('team')
            if len(name)<2 or not team_by_id(team):
                await ws.send_json({'type':'error','message':'Enter your name and select a team.'});return
            requested=str(raw.get('student_id',''))
            if requested in players:
                pid=requested
                players[pid].update(name=name, team=team, online=True)
            else:
                pid=uuid.uuid4().hex
                players[pid]={'id':pid,'name':name,'team':team,'online':True}
            await ws.send_json({'type':'joined','student_id':pid})
        clients[ws]={'role':role,'player_id':pid}
        await broadcast()
        while True:
            m=await ws.receive_json()
            async with lock:
                try:
                    if role=='instructor':
                        process_admin(m)
                    elif role=='student' and m.get('type')=='buzz':
                        p=players.get(pid)
                        if game['phase']!='buzz' or game['winner'] is not None or not p or p['team'] in game['locked_teams']:
                            continue
                        game['winner']={'id':pid,'name':p['name'],'team':p['team']}
                        game['phase']='locked'
                    else:
                        raise ValueError('This action is not permitted on this device.')
                except (ValueError,TypeError) as exc:
                    await ws.send_json({'type':'notice','message':str(exc)})
                    continue
                await broadcast()
    except (WebSocketDisconnect,RuntimeError):
        pass
    except Exception as ex:
        print('Websocket connection error:',repr(ex))
    finally:
        async with lock:
            clients.pop(ws,None)
            if pid and pid in players:
                # Mark offline only if no replacement socket is connected.
                players[pid]['online']=any(c.get('player_id')==pid for c in clients.values())
            await broadcast()


@app.get('/health')
def health():return {'ok':True,'question_count':len(QUESTIONS)}

@app.get('/api/public')
def public_info():return public_state()

@app.get('/api/qr')
def qr(url:str=''):
    if not url.startswith(('http://','https://')) or len(url)>400:
        raise HTTPException(400,'Invalid join URL')
    img=qrcode.make(url)
    buf=io.BytesIO();img.save(buf,format='PNG')
    return Response(buf.getvalue(),media_type='image/png',headers={'Cache-Control':'no-store'})

app.mount('/', StaticFiles(directory=HERE/'static',html=True),name='static')
