from fastapi.testclient import TestClient
from app import app,ROOM,game,players,history,initial_game
import pytest

@pytest.fixture(autouse=True)
def reset_game():
    game.clear();game.update(initial_game());players.clear();history.clear()


def get_state(ws):
    for _ in range(6):
        m=ws.receive_json()
        if m['type']=='state':return m['data']
    raise AssertionError('No state')


def test_question_bank_and_endpoint():
    with TestClient(app) as client:
        assert client.get('/health').json()['question_count']==61
        state=client.get('/api/public').json()
        assert len(state['board'])==2
        assert all(len(r['categories'])==6 for r in state['board'])
        assert all(len(c['tiles'])==5 for b in state['board'] for c in b['categories'])
        assert 'answer' not in str(state)
        assert client.get('/').status_code==200
        assert client.get('/app.js').status_code==200
        assert client.get('/api/qr',params={'url':'https://example.com'}).headers['content-type']=='image/png'


def test_live_game_buzzer_and_team_scoring():
  with TestClient(app) as client:
   with client.websocket_connect('/ws') as host:
    host.send_json({'type':'hello','role':'instructor','pin':'246810'})
    get_state(host)
    with client.websocket_connect('/ws') as s1:
     s1.send_json({'type':'hello','role':'student','name':'Student Alpha','room':ROOM,'team':'t1'})
     joined=s1.receive_json();assert joined['type']=='joined'
     get_state(s1);get_state(host)
     with client.websocket_connect('/ws') as s2:
      s2.send_json({'type':'hello','role':'student','name':'Student Beta','room':ROOM,'team':'t2'})
      assert s2.receive_json()['type']=='joined'
      get_state(s2);get_state(s1);get_state(host)
      host.send_json({'type':'select','id':'r1c1q1'})
      assert get_state(host)['phase']=='question';get_state(s1);get_state(s2)
      host.send_json({'type':'open_buzz'})
      assert get_state(host)['phase']=='buzz';get_state(s1);get_state(s2)
      s1.send_json({'type':'buzz'})
      assert get_state(host)['winner']['name']=='Student Alpha';get_state(s1);get_state(s2)
      s2.send_json({'type':'buzz'})
      host.send_json({'type':'judge','correct':False})
      v=get_state(host);assert v['phase']=='buzz' and v['teams'][0]['score']==-100
      assert 't1' in v['locked_teams'];get_state(s1);get_state(s2)
      s1.send_json({'type':'buzz'})
      s2.send_json({'type':'buzz'})
      v=get_state(host);assert v['winner']['name']=='Student Beta';get_state(s1);get_state(s2)
      host.send_json({'type':'judge','correct':True})
      v=get_state(host);assert v['phase']=='board' and v['teams'][1]['score']==100
      assert 'r1c1q1' in v['used']
      host.send_json({'type':'undo'})
      assert get_state(host)['phase']=='locked'


def test_final_wagers_and_scores():
 with TestClient(app) as client:
  with client.websocket_connect('/ws') as host:
   host.send_json({'type':'hello','role':'instructor','pin':'246810'})
   get_state(host)
   host.send_json({'type':'score','team':'t1','delta':1000});get_state(host)
   host.send_json({'type':'final_start'});s=get_state(host)
   assert s['current'] is None and s['phase']=='final_wager'
   host.send_json({'type':'final_wager','team':'t1','wager':600});s=get_state(host)
   assert s['final_wagers']['t1']==600
   host.send_json({'type':'final_reveal'});s=get_state(host)
   assert s['current']['id']=='final' and 'answer' not in str(s)
   host.send_json({'type':'final_grade','team':'t1','correct':False});s=get_state(host)
   assert s['teams'][0]['score']==400
   host.send_json({'type':'final_finish'});assert get_state(host)['phase']=='finished'
