"""Mock BFF server for testing device flow authentication."""
import json
import secrets
from http.server import HTTPServer, BaseHTTPRequestHandler

DEVICE_CODES = {}  # Store active device codes


class MockBFFHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = json.loads(self.rfile.read(content_length)) if content_length else {}

        if self.path == '/v1/auth/device':
            device_code = secrets.token_urlsafe(32)
            user_code = f"MOCK-{secrets.token_hex(2).upper()}"
            DEVICE_CODES[device_code] = user_code

            response = {
                "device_code": device_code,
                "user_code": user_code,
                "verification_uri": "http://localhost:8001/device",
                "verification_uri_complete": f"http://localhost:8001/device?code={user_code}",
                "expires_in": 1800,
                "interval": 5,
            }
            self._send_json(200, response)

        elif self.path == '/v1/auth/token':
            completion_code = body.get('completion_code', '')

            if completion_code.startswith('COMPLETE-'):
                response = {
                    "access_token": f"mock-access-{secrets.token_hex(16)}",
                    "refresh_token": f"mock-refresh-{secrets.token_hex(16)}",
                    "token_type": "Bearer",
                    "expires_in": 3600,
                    "scope": "read create_pending",
                }
                self._send_json(200, response)
            else:
                self._send_json(400, {"error": "invalid_grant"})

        elif self.path == '/v1/auth/refresh':
            response = {
                "access_token": f"mock-access-{secrets.token_hex(16)}",
                "refresh_token": f"mock-refresh-{secrets.token_hex(16)}",
                "token_type": "Bearer",
                "expires_in": 3600,
                "scope": "read create_pending",
            }
            self._send_json(200, response)
        else:
            self._send_json(404, {"error": "not_found"})

    def _send_json(self, status, data):
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def log_message(self, format, *args):
        print(f"[BFF] {args[0]}")


if __name__ == '__main__':
    server = HTTPServer(('localhost', 8001), MockBFFHandler)
    print("Mock BFF running on http://localhost:8001")
    print("Endpoints:")
    print("  POST /v1/auth/device - Start device flow")
    print("  POST /v1/auth/token  - Exchange completion code for tokens")
    print("  POST /v1/auth/refresh - Refresh tokens")
    print("\nAccepted completion codes: COMPLETE-*")
    server.serve_forever()
