"""Run: python -m unittest -v test_lab (from this examples directory).
Fake radio/BLE tests are software evidence, never a real-device test.
"""
import asyncio
import contextlib
import io
import importlib.util
import json
from pathlib import Path
import sys
import tempfile
import types
import unittest
from unittest.mock import patch
import lab_config
import protocol as p
import ble_client

CFG = {'schema': 1, 'ssid': 'Training-2G', 'password': 'test-only-pass'}


class Clock:
    now = 0
    def ticks_ms(self): return self.now
    def ticks_diff(self, a, b): return a - b


class Radio:
    def __init__(self): self.link, self.calls = False, []
    def active(self, v): self.calls.append(('active', v))
    def disconnect(self): self.link = False; self.calls.append(('disconnect',))
    def connect(self, s, w): self.calls.append(('connect', s, w))
    def isconnected(self): return self.link


class Store:
    def __init__(self, cfg=None, fail=False): self.cfg, self.fail = cfg, fail
    def load(self): return self.cfg, 'saved' if self.cfg else 'missing'
    def save(self, cfg):
        if self.fail: raise OSError('secret-shaped error must not escape')
        self.cfg = dict(cfg)


class UnitTests(unittest.TestCase):
    def lab(self, store=None):
        out, radio, clock = [], Radio(), Clock()
        lab = p.Lab(out.append, store or Store(), radio, clock)
        return lab, out, radio, clock

    def test_schema_utf8_and_types(self):
        self.assertEqual(lab_config.validate(CFG), CFG)
        for cfg in [dict(CFG, schema=True), dict(CFG, ssid='界'*11),
                    dict(CFG, password='short'), dict(CFG, password='字'*8),
                    dict(CFG, extra=1)]:
            with self.assertRaises(ValueError): lab_config.validate(cfg)

    def test_split_every_byte_and_invalid_overflow(self):
        cfg = dict(CFG, ssid='学习网络')
        raw = p.encode({'op': 'configure', 'config': cfg})
        parser, result = p.Lines(), []
        for byte in raw: result += parser.feed(bytes((byte,)))
        self.assertEqual(p.command(result[0]), ('configure', cfg))
        self.assertEqual(parser.buf, b'')
        with self.assertRaises(ValueError): p.Lines().feed(b'\xff\n')
        parser = p.Lines()
        with self.assertRaises(ValueError): parser.feed(b'x'*386)
        with self.assertRaises(ValueError): parser.feed(b'{}\n')

    def test_worst_case_escaped_valid_config_fits_frame(self):
        cfg={'schema':1,'ssid':'\0'*32,'password':'"'*63}
        lab_config.validate(cfg)
        raw=p.encode({'op':'configure','config':cfg})
        self.assertLessEqual(len(raw)-1,p.LIMIT)
        parser=p.Lines();result=[]
        for i in range(0,len(raw),20):result+=parser.feed(raw[i:i+20])
        self.assertEqual(p.command(result[0]),('configure',cfg))

    def test_notify_state_order_and_no_secret(self):
        lab, out, radio, _ = self.lab()
        lab.receive({'op': 'configure', 'config': CFG})
        self.assertEqual([s['state'] for s in out], ['accepted', 'saved'])
        self.assertNotIn(('connect', CFG['ssid'], CFG['password']), radio.calls)
        lab.step(); self.assertEqual(lab.state, 'joining')
        lab.step(); self.assertEqual(lab.state, 'joining')
        radio.link = True; lab.step()
        self.assertEqual([s['state'] for s in out], ['accepted','saved','joining','connected'])
        serialized = json.dumps(out)
        self.assertNotIn(CFG['ssid'], serialized); self.assertNotIn(CFG['password'], serialized)

    def test_timeout_save_failure_busy_and_restart(self):
        lab, out, radio, clock = self.lab(Store(CFG))
        lab.step(); lab.receive({'op':'configure','config':CFG})
        self.assertEqual(out[-1]['state'], 'busy')
        clock.now = 15000; lab.step(); self.assertEqual(lab.state, 'timeout')
        failed, out, _, _ = self.lab(Store(fail=True))
        failed.receive({'op':'configure','config':CFG})
        self.assertEqual([s['state'] for s in out], ['accepted','save_failed'])
        self.assertFalse(failed.configured)
        store = Store()
        before, _, _, _ = self.lab(store)
        before.receive({'op':'configure','config':CFG})
        after, out, radio, _ = self.lab(store)
        self.assertEqual(after.state, 'saved'); after.step()
        self.assertEqual(radio.calls[-1], ('connect',CFG['ssid'],CFG['password']))
        radio.link=True;after.step();self.assertEqual(after.state,'connected')

    def test_redaction_and_bad_commands(self):
        lab,out,_,_=self.lab()
        for cmd in [None, {'op':'status','password':'secret'}, {'op':'configure','config':{}}]:
            lab.receive(cmd);self.assertEqual(out[-1]['state'],'invalid')
        with self.assertRaises(ValueError):p.safe_status(dict(out[-1],password='secret'))
        with self.assertRaises(ValueError):p.safe_status(dict(out[-1],v=2))

    def test_inactive_radio_disconnect_and_driver_error(self):
        class Inactive(Radio):
            def disconnect(self):raise OSError('WiFi not started')
        radio=Inactive();out=[];clock=Clock()
        lab=p.Lab(out.append,Store(),radio,clock)
        self.assertEqual(lab.state,'missing')
        lab.receive({'op':'configure','config':CFG});lab.step()
        self.assertEqual(lab.state,'joining')
        with patch.object(radio,'isconnected',side_effect=OSError('radio error')):lab.step()
        self.assertEqual(lab.state,'connect_failed')

    def test_hidden_password_no_echo_fallback(self):
        with patch('builtins.input',return_value=CFG['ssid']), patch('getpass.getpass',return_value=CFG['password']):
            self.assertEqual(ble_client.credentials(),CFG)
        def fallback(*args):
            import warnings,getpass
            warnings.warn('Cannot hide',getpass.GetPassWarning)
            return 'bad'
        with patch('builtins.input',return_value=CFG['ssid']),patch('getpass.getpass',side_effect=fallback):
            with self.assertRaises(Warning):ble_client.credentials()

    def test_file_load_and_limited_clear(self):
        with tempfile.TemporaryDirectory() as d:
            path=Path(d)/'lab_wifi.json';other=Path(d)/'main.py';other.write_text('preserve')
            path.write_text(json.dumps(CFG));self.assertEqual(lab_config.load(str(path))[0],CFG)
            path.write_text('x'*385);self.assertEqual(lab_config.load(str(path))[1],'invalid')
            lab_config.clear(str(path),types.SimpleNamespace(WLAN=lambda _:Radio()))
            self.assertEqual(other.read_text(),'preserve')


class FakeClient:
    def __init__(self, mismatch=False):
        self.rx=types.SimpleNamespace(uuid=p.RX,properties=['write'])
        self.tx=types.SimpleNamespace(uuid=p.TX,properties=['notify'])
        service=types.SimpleNamespace(characteristics=[self.rx,self.tx])
        self.services=types.SimpleNamespace(get_service=lambda _:None if mismatch else service)
        self.calls=[];self.parser=p.Lines();self.callback=None
    async def start_notify(self,tx,callback):self.calls.append('subscribe');self.callback=callback
    async def stop_notify(self,tx):self.calls.append('stop')
    def emit(self,state):
        raw=p.encode({'v':1,'state':state,'configured':state!='ready'})
        for i in range(0,len(raw),20):self.callback(self.tx,bytearray(raw[i:i+20]))
    async def write_gatt_char(self,rx,data,response):
        assert self.callback and response and len(data)<=20
        self.calls.append('write')
        for cmd in self.parser.feed(data):
            if cmd['op']=='hello':self.emit('ready')
            elif cmd['op']=='status':self.emit('connected')
            else:
                for s in ['accepted','saved','joining','connected']:self.emit(s)


class ClientTests(unittest.IsolatedAsyncioTestCase):
    async def test_subscribe_first_chunked_write_and_notify_reassembly(self):
        client=FakeClient();output=io.StringIO()
        with contextlib.redirect_stdout(output):seen=await ble_client.session(client,CFG)
        self.assertEqual(client.calls[0],'subscribe')
        self.assertEqual(seen,['accepted','saved','joining','connected'])
        self.assertNotIn(CFG['password'],output.getvalue())
        self.assertNotIn(CFG['ssid'],output.getvalue())
    async def test_cache_mismatch_sends_nothing(self):
        client=FakeClient(mismatch=True)
        with self.assertRaises(ValueError):await ble_client.session(client,CFG)
        self.assertEqual(client.calls,[])
    async def test_status_is_notification_callback(self):
        client=FakeClient()
        with contextlib.redirect_stdout(io.StringIO()):result=await ble_client.session(client)
        self.assertEqual(result,['connected']);self.assertEqual(client.calls[0],'subscribe')

    async def test_absolute_deadline_stops_even_with_queued_notifications(self):
        client=FakeClient()
        loop_clock=types.SimpleNamespace(time=unittest.mock.Mock(side_effect=[0,1,26]))
        with patch('ble_client.asyncio.get_running_loop',return_value=loop_clock),contextlib.redirect_stdout(io.StringIO()) as output:
            with self.assertRaises(asyncio.TimeoutError):await ble_client.session(client,CFG)
        self.assertEqual(client.calls[-1],'stop')
        self.assertIn('accepted',output.getvalue());self.assertNotIn('connected',output.getvalue())


class FakeBLE:
    def __init__(self):self.buffer=b'';self.notifications=[];self.disconnected=[];self.active_calls=[]
    def active(self,v):self.active_calls.append(v)
    def config(self,**kwargs):pass
    def gatts_register_services(self,services):return ((101,102),)
    def gatts_set_buffer(self,handle,size,append):assert handle==102 and size==512 and append
    def irq(self,callback):self.callback=callback
    def gap_advertise(self,interval,**kwargs):
        assert interval==500000 and len(kwargs['adv_data'])<=31 and len(kwargs['resp_data'])<=31
    def gap_disconnect(self,conn):self.disconnected.append(conn)
    def gatts_read(self,handle):raw,self.buffer=self.buffer,b'';return raw
    def gatts_notify(self,conn,handle,data):self.notifications.append((conn,handle,bytes(data)))
    def write(self,raw):self.buffer=raw;self.callback(3,(1,102))


class AdapterTests(unittest.TestCase):
    def adapter(self):
        fake_bt=types.SimpleNamespace(UUID=lambda _:b'u'*16)
        spec=importlib.util.spec_from_file_location('c12_board_test',Path(__file__).with_name('ble_setup.py'))
        module=importlib.util.module_from_spec(spec)
        with patch.dict(sys.modules,{'bluetooth':fake_bt,'network':types.SimpleNamespace()}):spec.loader.exec_module(module)
        ble=FakeBLE();peer=module.Peripheral(ble);ble.callback(1,(1,0,b'addr'))
        lab=p.Lab(peer.emit,Store(),Radio(),Clock())
        return peer,ble,lab
    def test_real_adapter_notify_chunks_and_no_echo(self):
        peer,ble,lab=self.adapter();peer.receive(lab)
        ble.write(p.encode({'op':'hello'}));peer.receive(lab)
        raw=p.encode({'op':'configure','config':CFG})
        for i in range(0,len(raw),20):ble.write(raw[i:i+20]);peer.receive(lab)
        while peer.out:peer.send_one()
        received=p.Lines().feed(b''.join(x[2] for x in ble.notifications))
        self.assertEqual([v['state'] for v in received],['ready','accepted','saved'])
        self.assertTrue(all(len(x[2])<=20 and x[:2]==(1,101) for x in ble.notifications))
        self.assertNotIn(CFG['password'],json.dumps(received))
    def test_no_configuration_before_handshake(self):
        peer,ble,lab=self.adapter();peer.receive(lab)
        ble.write(p.encode({'op':'configure','config':CFG}));peer.receive(lab)
        self.assertFalse(lab.configured);self.assertEqual(peer.out,[])
    def test_disconnect_discards_partial_credentials(self):
        peer,ble,lab=self.adapter();peer.receive(lab)
        ble.write(b'{"op":"configure",');peer.receive(lab)
        ble.callback(2,(1,0,b'addr'));peer.receive(lab)
        ble.callback(1,(1,0,b'addr'));peer.receive(lab)
        self.assertEqual(peer.lines.buf,b'');self.assertFalse(peer.session_ready)
        ble.write(p.encode({'op':'hello'}));peer.receive(lab)
        self.assertTrue(peer.session_ready);self.assertFalse(lab.configured)
    def test_oversize_disconnect_and_extra_central(self):
        peer,ble,lab=self.adapter();peer.receive(lab)
        ble.callback(1,(2,0,b'other'));self.assertIn(2,ble.disconnected)
        ble.write(b'x'*386);peer.receive(lab)
        self.assertIn(1,ble.disconnected);self.assertFalse(lab.configured)


if __name__=='__main__':unittest.main()
