"""ML-C11 local SoftAP lab; MicroPython v1.29.0 ESP32. No TLS/captive DNS.

Use only temporary/private WPA2 lab credentials. The generated AP key is
shown once on the local USB console; target SSID/password are never printed.
"""
import json
import os
import socket
import lab_config

AP_SSID = 'Molo-Setup-C11'
AP_IP = '192.168.4.1'
JOIN_MS = 15000
SETUP_MS = 300000
MAX_HEADER = 2048
MAX_BODY = 1024

FORM = '''<!doctype html><html lang="en"><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Molo C11 local setup</title><style>
*{box-sizing:border-box}body{font:18px system-ui;color:#081f58;background:#fffaf2;
max-width:560px;margin:32px auto;padding:20px}input,button{font:inherit;width:100%;
padding:12px;margin:8px 0 20px}button{background:#075ccc;color:white;border:0}
label{display:block}p{line-height:1.5}small{display:block}</style>
<h1>Connect the board</h1><p>You are on the temporary setup Wi-Fi.
Enter the <b>target 2.4 GHz WPA2 lab router</b> below.</p>
<p>This local HTTP lab has no TLS. Use temporary lab credentials only.</p>
<form method="post" action="/configure" autocomplete="off">
<input type="hidden" name="token" value="__TOKEN__">
<label>Target router name (SSID)<input name="ssid" required maxlength="32"
autocomplete="off" autocapitalize="none" spellcheck="false"></label>
<label>Target router passphrase<input type="password" name="password" required
minlength="8" maxlength="63" autocomplete="new-password"></label>
<small>SSID: 1–32 UTF-8 bytes. Passphrase: 8–63 printable ASCII characters.</small>
<button>Submit and try connection</button></form>
<p>The receipt confirms submission only. Read the redacted USB result.
The setup network may drop while the board joins your router.</p>
<script>const f=document.querySelector('form'),s=f.elements.ssid,p=f.elements.password;
function check(){s.setCustomValidity(new TextEncoder().encode(s.value).length>32?
'Use at most 32 UTF-8 bytes':'');p.setCustomValidity(/^[\\x20-\\x7e]{8,63}$/.test(p.value)?
'':'Use 8 to 63 printable ASCII characters');}f.addEventListener('input',check);
f.addEventListener('submit',e=>{check();if(!f.reportValidity())e.preventDefault();});</script></html>'''

RECEIPT = '''<!doctype html><html lang="en"><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Submission received</title><body><h1>Submission received</h1>
<p>Connection is not confirmed yet. Wait up to 15 seconds and read the USB result.
The setup Wi-Fi may drop. Rejoin it if the attempt fails; a successful connection
closes it. No credentials are shown in this page.</p></body></html>'''


def _hex(count):
    return ''.join('%02x' % b for b in os.urandom(count))


def decode_field(value):
    output = bytearray()
    i = 0
    while i < len(value):
        char = value[i]
        if char == 43:
            output.append(32)
        elif char == 37:
            if i + 2 >= len(value):
                raise ValueError('Invalid form encoding')
            pair = value[i + 1:i + 3]
            if any(c not in b'0123456789abcdefABCDEF' for c in pair):
                raise ValueError('Invalid form encoding')
            output.append(int(pair, 16))
            i += 2
        else:
            output.append(char)
        i += 1
    return output.decode('utf-8')


def parse_form(body, token):
    if len(body) > MAX_BODY:
        raise ValueError('Form too large')
    fields = {}
    for pair in body.split(b'&'):
        if b'=' not in pair:
            raise ValueError('Invalid form')
        key, value = pair.split(b'=', 1)
        key = decode_field(key)
        if key in fields:
            raise ValueError('Duplicate field')
        fields[key] = decode_field(value)
    if set(fields) != {'ssid', 'password', 'token'} or fields['token'] != token:
        raise ValueError('Invalid form session')
    return lab_config.validate({'schema': 1, 'ssid': fields['ssid'], 'password': fields['password']})


def read_request(client, clock=None):
    if clock is None:
        import time as clock
    def now():
        return clock.ticks_ms() if hasattr(clock, 'ticks_ms') else int(clock.monotonic() * 1000)
    began = now()
    def receive(count):
        current = now()
        elapsed = clock.ticks_diff(current, began) if hasattr(clock, 'ticks_diff') else current - began
        remaining = 3000 - elapsed
        if remaining <= 0:
            raise OSError('Request timed out')
        client.settimeout(remaining / 1000)
        return client.recv(count)
    raw = b''
    while b'\r\n\r\n' not in raw:
        part = receive(256)
        if not part:
            raise ValueError('Incomplete request')
        raw += part
        if len(raw.split(b'\r\n\r\n', 1)[0]) > MAX_HEADER:
            raise ValueError('Header too large')
    head, body = raw.split(b'\r\n\r\n', 1)
    lines = head.split(b'\r\n')
    request = lines[0].decode('ascii').split(' ')
    if len(request) != 3 or request[2] not in ('HTTP/1.0', 'HTTP/1.1'):
        raise ValueError('Invalid request')
    headers = {}
    for line in lines[1:]:
        if b':' not in line:
            raise ValueError('Invalid header')
        key, value = line.split(b':', 1)
        key = key.decode('ascii').strip().lower()
        if key in headers:
            raise ValueError('Duplicate header')
        headers[key] = value.decode('ascii').strip()
    if 'transfer-encoding' in headers:
        raise ValueError('Unsupported request framing')
    length_text = headers.get('content-length', '0')
    if not length_text.isdigit():
        raise ValueError('Invalid content length')
    length = int(length_text)
    if length > MAX_BODY or len(body) > length:
        raise ValueError('Invalid body size')
    while len(body) < length:
        part = receive(min(256, length - len(body)))
        if not part:
            raise ValueError('Incomplete body')
        body += part
    return request[0], request[1], headers, body


def response(code, body):
    reason = {200:'OK', 202:'Accepted', 400:'Bad Request', 404:'Not Found'}[code]
    payload = body.encode('utf-8')
    header = ('HTTP/1.1 %s %s\r\nContent-Type: text/html; charset=utf-8\r\n'
              'Content-Length: %s\r\nConnection: close\r\nCache-Control: no-store\r\n'
              'Referrer-Policy: no-referrer\r\nX-Content-Type-Options: nosniff\r\n'
              'Content-Security-Policy: default-src \'none\'; style-src \'unsafe-inline\'; '
              'script-src \'unsafe-inline\'; form-action \'self\'; frame-ancestors \'none\'\r\n\r\n')
    return (header % (code, reason, len(payload))).encode('ascii') + payload


def handle(client, token, address=AP_IP):
    candidate = None
    try:
        method, target, headers, body = read_request(client)
        if headers.get('host') not in (address, address + ':80'):
            raise ValueError('Wrong local host')
        if headers.get('origin', 'http://' + address) != 'http://' + address:
            raise ValueError('Wrong local origin')
        if method == 'GET' and target == '/' and not body:
            reply = response(200, FORM.replace('__TOKEN__', token))
        elif method == 'POST' and target == '/configure':
            if headers.get('content-type', '').split(';', 1)[0] != 'application/x-www-form-urlencoded':
                raise ValueError('Unsupported form')
            candidate = parse_form(body, token)
            reply = response(202, RECEIPT)
        else:
            reply = response(404, '<h1>Open the local setup address</h1>')
    except (ValueError, UnicodeError, OSError):
        candidate = None
        reply = response(400, '<h1>Form not accepted</h1><p>Reopen the setup page and try again.</p>')
    try:
        client.sendall(reply)
    except OSError:
        candidate = None
    finally:
        client.close()
    # The caller must not switch Wi-Fi before sendall and close complete.
    return candidate


def join(sta, cfg, clock, timeout_ms=JOIN_MS):
    try:
        sta.active(True)
        sta.disconnect()
        sta.connect(cfg['ssid'], cfg['password'])
        began = clock.ticks_ms()
        while clock.ticks_diff(clock.ticks_ms(), began) < timeout_ms:
            if sta.isconnected() and sta.ifconfig()[0] not in ('0.0.0.0', '', None):
                return True
            clock.sleep_ms(100)
    except OSError:
        pass
    try:
        sta.disconnect()
        sta.active(False)
    except OSError:
        pass
    return False


def try_candidate(sta, cfg, clock, path=lab_config.CONFIG_PATH):
    if not join(sta, cfg, clock):
        return {'state': 'join_failed', 'configured': lab_config.load(path)[0] is not None, 'ip_assigned': False}
    try:
        lab_config.save(cfg, path)
    except OSError:
        sta.disconnect()
        sta.active(False)
        return {'state': 'save_failed', 'configured': lab_config.load(path)[0] is not None, 'ip_assigned': False}
    return {'state': 'connected', 'configured': True, 'ip_assigned': True}


def status(path=lab_config.CONFIG_PATH, network_module=None):
    if network_module is None:
        import network as network_module
    cfg, state = lab_config.load(path)
    sta = network_module.WLAN(network_module.WLAN.IF_STA)
    linked = sta.isconnected()
    return {'config_state': state, 'configured': cfg is not None,
            'link_up': bool(linked), 'ip_assigned': bool(linked and sta.ifconfig()[0] not in ('0.0.0.0', '', None))}


def clear(path=lab_config.CONFIG_PATH):
    import network
    lab_config.clear(path)
    sta = network.WLAN(network.WLAN.IF_STA)
    sta.disconnect()
    sta.active(False)
    network.WLAN(network.WLAN.IF_AP).active(False)
    return {'state': 'cleared', 'configured': False, 'ip_assigned': False}


def run(force_setup=False, path=lab_config.CONFIG_PATH):
    import network
    import time
    sta = network.WLAN(network.WLAN.IF_STA)
    ap = network.WLAN(network.WLAN.IF_AP)
    ap.active(False)
    cfg, _ = lab_config.load(path)
    if not force_setup and cfg is not None:
        if join(sta, cfg, time):
            print(json.dumps({'state': 'reconnected', 'configured': True, 'ip_assigned': True}))
            return
        print(json.dumps({'state': 'saved_join_failed', 'ip_assigned': False}))
    sta.active(False)
    token, setup_key = _hex(16), _hex(8)
    server = None
    try:
        ap.active(True)
        ap.config(ssid=AP_SSID, security=3, key=setup_key, max_clients=1)
        if ap.config('security') != 3:
            raise OSError('Protected setup AP unavailable')
        ap.ifconfig((AP_IP, '255.255.255.0', AP_IP, AP_IP))
        server = socket.socket()
        address = socket.getaddrinfo(AP_IP, 80, socket.AF_INET, socket.SOCK_STREAM)[0][-1]
        server.bind(address)
        server.listen(1)
        server.settimeout(1)
        # This is the new temporary AP secret, NOT the target-router passphrase.
        print('SETUP SSID: ' + AP_SSID)
        print('SETUP KEY (private USB only): ' + setup_key)
        print('OPEN http://' + AP_IP + '/  (setup expires in five minutes)')
        began = time.ticks_ms()
        while time.ticks_diff(time.ticks_ms(), began) < SETUP_MS:
            try:
                client, _ = server.accept()
            except OSError:
                continue
            candidate = handle(client, token)
            if candidate is None:
                continue
            time.sleep_ms(300)
            result = try_candidate(sta, candidate, time, path)
            candidate = None
            print(json.dumps(result))
            if result['state'] == 'connected':
                return
            print('RETRY: rejoin the setup Wi-Fi and reopen the local page.')
        print(json.dumps({'state': 'setup_expired', 'ip_assigned': False}))
    except OSError:
        print(json.dumps({'state': 'setup_error', 'ip_assigned': False}))
    finally:
        if server is not None:
            server.close()
        ap.active(False)
