"""Local-only TLS pairing QR. No key files, network calls or persistent QR images."""
import re
import tkinter as tk
from tkinter import ttk
from urllib.parse import urlencode


def pairing_payload(host, port, fingerprint, token=None):
    host = host.strip()
    if (not 1 <= len(host) <= 253 or not re.fullmatch(r"[A-Za-z0-9._:%-]+", host)
            or host in ("0.0.0.0", "::", "0:0:0:0:0:0:0:0")):
        raise ValueError("Enter this PC's LAN IP or hostname, not 0.0.0.0. For the Android emulator use 10.0.2.2.")
    if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:
        raise ValueError("Port must be 1..65535")
    fingerprint = fingerprint.upper()
    if not re.fullmatch(r"[0-9A-F]{64}", fingerprint):
        raise ValueError("A valid certificate SHA-256 fingerprint is required")
    fields = dict(v="1", mode="tls", host=host, port=str(port), sha256=fingerprint)
    if token is not None:
        if len(token) > 256 or any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in token):
            raise ValueError("Token must be at most 256 characters with no control characters")
        fields["token"] = token
    payload = "mangolink://pair?" + urlencode(fields)
    if len(payload) > 2048:
        raise ValueError("Pairing details are too long")
    return payload


def qr_matrix(payload):
    try:
        import qrcode
    except ImportError as exc:
        raise RuntimeError("QR pairing requires: py -3 -m pip install -r requirements-qr.txt") from exc
    code = qrcode.QRCode(error_correction=qrcode.constants.ERROR_CORRECT_M, border=4, box_size=1)
    code.add_data(payload)
    code.make(fit=True)
    return code.get_matrix()


class PairingDialog(tk.Toplevel):
    def __init__(self, parent, host, port, fingerprint, token):
        super().__init__(parent)
        self.title("Pair MangoLink over TLS")
        self.transient(parent)
        self.grab_set()
        self.port, self.fingerprint, self.token = port, fingerprint, token
        self.image = None
        self.payload = None
        body = ttk.Frame(self, padding=16)
        body.pack(fill="both", expand=True)
        ttk.Label(body, text="Scan this screen in MangoLink → Connection settings.", wraplength=460).pack(anchor="w")
        ttk.Label(body, text="PC LAN IP / hostname (Android emulator: 10.0.2.2)").pack(anchor="w", pady=(12, 0))
        self.host = tk.StringVar(value=host if host not in ("0.0.0.0", "::") else "")
        ttk.Entry(body, textvariable=self.host, width=48).pack(fill="x")
        self.include_token = tk.BooleanVar(value=True)
        ttk.Checkbutton(body, text="Include session token", variable=self.include_token).pack(anchor="w", pady=8)
        ttk.Label(body, text="Includes the public certificate fingerprint. Keep this QR private when it includes the token.",
                  wraplength=460).pack(anchor="w")
        ttk.Button(body, text="Generate / update QR code", command=self.generate).pack(pady=8)
        self.display = ttk.Label(body, text="Enter the PC LAN IP, then generate the QR code.", anchor="center")
        self.display.pack(fill="both", expand=True)
        ttk.Label(body, text="On the phone: review the details, then tap Connect. The private key stays on the PC.",
                  wraplength=460).pack(anchor="w", pady=8)
        ttk.Button(body, text="Close", command=self.destroy).pack()
        self.host.trace_add("write", self.invalidate)
        self.include_token.trace_add("write", self.invalidate)
        if self.host.get():
            self.generate()

    def invalidate(self, *_):
        self.payload = None
        self.image = None
        self.display.config(image="", text="Details changed. Generate an updated QR code.")

    def generate(self):
        self.invalidate()
        try:
            payload = pairing_payload(self.host.get(), self.port, self.fingerprint,
                                      self.token if self.include_token.get() else None)
            matrix = qr_matrix(payload)
            size = len(matrix)
            image = tk.PhotoImage(master=self, width=size, height=size)
            image.put(" ".join("{" + " ".join("black" if cell else "white" for cell in row) + "}" for row in matrix))
            self.image = image.zoom(max(2, 420 // size))
            self.display.config(image=self.image, text="")
            self.payload = payload
        except (ValueError, RuntimeError) as exc:
            self.display.config(text=str(exc), wraplength=460)
