"""Minstrel setup app.

Spotify pairs with a Connect device only when it finds it on the local network. A hosted Minstrel bot isn't
on yours, so this app:
  1. sends the bot your Soloist key (Spotify's keys are personal, so your device runs on yours),
  2. announces your device on your network for a few minutes, and
  3. relays Spotify's pairing requests to the bot.
The login Spotify sends while pairing is encrypted to the bot's Spotify player, so this app can't read it.

Run it with the link from the bot's /pair command (or name the exe "Minstrel Setup (CODE).exe", which the
bot's download does). --cli forces the text version.
"""
import http.server
import json
import os
import queue
import re
import secrets
import socket
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser

from zeroconf import IPVersion, ServiceInfo, Zeroconf

try:  # written by build.py: the bot this copy of the app was built for
    from minstrel_server import SERVER
except ImportError:
    SERVER = None

KEY_PAGE = "https://developer.spotify.com/dashboard/soloist"
SERVICE = "_spotify-connect._tcp.local."
TIMEOUT_S = 30 * 60


class SetupError(Exception):
    pass


# ── Talking to the bot ───────────────────────────────────────────────────────

def fetch(url, data=None, headers=None, timeout=30):
    """(status, content type, body) without raising on HTTP errors."""
    req = urllib.request.Request(url, data=data, headers=headers or {}, method="POST" if data is not None else "GET")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return r.status, r.headers.get("Content-Type", ""), r.read()
    except urllib.error.HTTPError as e:
        return e.code, e.headers.get("Content-Type", ""), e.read()


def error_of(body, status):
    try:
        return json.loads(body).get("error") or f"The bot answered HTTP {status}."
    except ValueError:
        return f"The bot answered HTTP {status}."


def parse_link(link):
    """(base URL, code) from https://host/pair/CODE."""
    u = urllib.parse.urlparse(link.strip())
    parts = u.path.strip("/").split("/")
    if u.scheme not in ("http", "https") or len(parts) < 2 or parts[-2] != "pair":
        raise SetupError("That doesn't look like a Minstrel setup link (https://.../pair/XXXXXXXX).")
    return f"{u.scheme}://{u.netloc}", parts[-1].upper()


def link_from_exe_name():
    """The bot's download is named "Minstrel Setup (CODE).exe" (browsers may add " (1)")."""
    if not (getattr(sys, "frozen", False) and SERVER):
        return None
    m = re.search(r"\(([A-Z2-9]{8})\)", os.path.basename(sys.executable))
    return f"{SERVER}/pair/{m.group(1)}" if m else None


class Bot:
    def __init__(self, link):
        self.base, self.code = parse_link(link)
        self.url = f"{self.base}/pair/{self.code}"

    def status(self):
        try:
            status, _, body = fetch(f"{self.url}/status")
        except OSError as e:
            raise SetupError(f"Couldn't reach the bot at {self.base}: {e}")
        if status == 410:
            raise SetupError("This setup link has expired. Run /pair in Discord for a new one.")
        if status != 200:
            raise SetupError(error_of(body, status))
        return json.loads(body)

    def set_key(self, key):
        data = json.dumps({"key": key.strip()}).encode()
        try:
            status, _, body = fetch(f"{self.url}/key", data, {"Content-Type": "application/json"}, timeout=60)
        except OSError as e:
            raise SetupError(f"Couldn't reach the bot: {e}")
        if status != 200:
            raise SetupError(error_of(body, status))
        return json.loads(body)


# ── Announcing the device and relaying pairing ────────────────────────────────

def lan_ip():
    """This computer's address on the network it uses to reach the internet (no packets are sent)."""
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.connect(("192.0.2.1", 9))
        return s.getsockname()[0]


class Pairing:
    """Announces the device on this network and relays Spotify's pairing calls to the bot.
    Progress goes to `report(event, detail)`: found, login, refused, paired, expired."""

    def __init__(self, bot, device_name, report):
        self.bot, self.device_name, self.report = bot, device_name, report
        self.found = self.sent_login = False
        self.done = threading.Event()

    def _handler(self):
        pairing = self

        class Relay(http.server.BaseHTTPRequestHandler):
            def _relay(self, body=None):
                path = urllib.parse.urlparse(self.path)
                if path.path.rstrip("/") != "/zc":
                    self.send_error(404)
                    return
                # getInfo comes as ?action=getInfo; addUser is a form POST with the action in the body.
                fields = urllib.parse.parse_qs(path.query) or urllib.parse.parse_qs((body or b"").decode("ascii", "replace"))
                action = fields.get("action", [""])[0]
                headers = {"Content-Type": self.headers.get("Content-Type", "application/x-www-form-urlencoded")} if body is not None else {}
                try:
                    status, ctype, out = fetch(f"{pairing.bot.url}/zc?{path.query}", body, headers)
                except OSError as e:
                    status, ctype, out = 502, "application/json", json.dumps({"status": 102, "statusString": str(e)}).encode()
                if action == "getInfo" and not pairing.found:
                    pairing.found = True
                    pairing.report("found", None)
                if action == "addUser":
                    try:
                        answer = json.loads(out)
                    except ValueError:
                        answer = {}
                    if status == 200 and answer.get("status", 101) == 101:
                        pairing.sent_login = True
                        pairing.report("login", None)
                    else:
                        pairing.report("refused", answer.get("statusString") or f"HTTP {status}")
                self.send_response(status)
                self.send_header("Content-Type", ctype or "application/json")
                self.send_header("Content-Length", str(len(out)))
                self.end_headers()
                self.wfile.write(out)

            def do_GET(self):
                self._relay()

            def do_POST(self):
                n = int(self.headers.get("Content-Length") or 0)
                self._relay(self.rfile.read(min(n, 64 * 1024)))

            def log_message(self, *args):
                pass

        return Relay

    def run(self):
        """Blocks until paired, timed out or stop() is called."""
        server = http.server.ThreadingHTTPServer(("0.0.0.0", 0), self._handler())
        threading.Thread(target=server.serve_forever, daemon=True).start()
        ip = lan_ip()
        zc = Zeroconf(interfaces=[ip], ip_version=IPVersion.V4Only)
        service = ServiceInfo(
            SERVICE, f"{secrets.token_hex(16)}.{SERVICE}",
            addresses=[socket.inet_aton(ip)], port=server.server_address[1],
            properties={"CPath": "/zc", "VERSION": "1.0", "Stack": "SP"},
            server=f"minstrel-setup-{secrets.token_hex(3)}.local.",
        )
        zc.register_service(service)
        try:
            deadline = time.time() + TIMEOUT_S
            while time.time() < deadline and not self.done.wait(2):
                if not self.sent_login:
                    continue
                try:
                    if self.bot.status().get("loggedIn"):
                        self.report("paired", None)
                        return True
                except SetupError:
                    # The bot retires the link once the device logs in.
                    self.report("paired", None)
                    return True
            if not self.done.is_set():
                self.report("expired", None)
            return False
        finally:
            zc.unregister_service(service)
            zc.close()
            server.shutdown()

    def stop(self):
        self.done.set()


# ── Text version ─────────────────────────────────────────────────────────────

def run_cli(link):
    print("Minstrel setup\n")
    link = link or link_from_exe_name() or input("Paste the setup link from the bot's /pair command: ")
    try:
        bot = Bot(link)
        info = bot.status()
        name = info["deviceName"]
        if not info.get("hasKey") or input("Use a new Spotify key? Enter = keep the current one, y = new: ").strip().lower() == "y":
            print(f"\nMinstrel plays through your own Spotify, using a developer key made by you (needs Premium).\n"
                  f"1. Open {KEY_PAGE} and log in with the Spotify account you'll play from.\n"
                  f"2. Create a Soloist API key and copy it.\n")
            import getpass
            info = bot.set_key(getpass.getpass("Paste the key (hidden): "))
            print("Key saved and your device is running.\n")
        if info.get("loggedIn") and input(f"{name} is already linked to Spotify, so you're set. "
                                          "Pair a different Spotify account? (y/N): ").strip().lower() != "y":
            return 0
    except SetupError as e:
        print(f"\n{e}")
        return 1

    def report(event, detail):
        print({
            "found": "  Spotify found the device.",
            "login": "  Spotify sent its login; passing it to the bot...",
            "refused": f"  Spotify's login was refused ({detail}). Check your key, run /pair again and retry.",
            "paired": f"\nPaired! {name} is linked to your Spotify. Join a voice channel in Discord and pick it in Spotify.",
            "expired": "\nTimed out. Run /pair in Discord for a new link and try again.",
        }[event])

    pairing = Pairing(bot, name, report)
    print(f"Now open the Spotify app (desktop app here, or your phone on the same Wi-Fi), open the devices list and "
          f"pick {name}. The web player can't do this step.")
    print("If Windows asks whether to allow network access, choose Allow. Waiting... (Ctrl+C to stop)")
    try:
        return 0 if pairing.run() else 1
    except KeyboardInterrupt:
        pairing.stop()
        return 1


# ── Window version ───────────────────────────────────────────────────────────

def run_gui(link):
    import tkinter as tk
    from tkinter import ttk

    root = tk.Tk()
    root.title("Minstrel setup")
    root.geometry("560x470")
    root.minsize(480, 420)
    style = ttk.Style(root)
    if "vista" in style.theme_names():
        style.theme_use("vista")
    style.configure("Title.TLabel", font=("Segoe UI", 16, "bold"))
    style.configure("Body.TLabel", font=("Segoe UI", 10), wraplength=500)
    style.configure("Status.TLabel", font=("Segoe UI", 10, "bold"), wraplength=500)
    style.configure("Error.TLabel", font=("Segoe UI", 10), foreground="#b3261e", wraplength=500)

    events = queue.Queue()  # callables from worker threads, run on the UI thread
    state = {"bot": None, "info": None, "pairing": None}
    frame = ttk.Frame(root, padding=24)
    frame.pack(fill="both", expand=True)

    def ui(fn):
        events.put(fn)

    def pump():
        while not events.empty():
            events.get()()
        root.after(100, pump)

    def page(title):
        for w in frame.winfo_children():
            w.destroy()
        ttk.Label(frame, text=title, style="Title.TLabel").pack(anchor="w", pady=(0, 12))

    def text(s, style_="Body.TLabel", pady=(0, 8)):
        lbl = ttk.Label(frame, text=s, style=style_, justify="left")
        lbl.pack(anchor="w", pady=pady)
        return lbl

    def background(work, done, fail):
        def run():
            try:
                result = work()
            except SetupError as e:
                msg = str(e)
                ui(lambda: fail(msg))
            except Exception as e:  # keep the window alive whatever happens
                msg = f"Something went wrong: {e}"
                ui(lambda: fail(msg))
            else:
                ui(lambda: done(result))
        threading.Thread(target=run, daemon=True).start()

    # 1. The link
    def link_page(error=None, prefill=""):
        page("Set up Minstrel")
        text("Paste the setup link the bot gave you when you ran /pair in Discord.")
        entry = ttk.Entry(frame, font=("Segoe UI", 10))
        entry.pack(fill="x", pady=(0, 8))
        entry.insert(0, prefill)
        err = text(error or "", "Error.TLabel")

        def go():
            try:
                state["bot"] = Bot(entry.get())
            except SetupError as e:
                err.config(text=str(e))
                return
            check_link()

        ttk.Button(frame, text="Continue", command=go).pack(anchor="e", pady=(12, 0))
        entry.focus()

    def check_link():
        page("Set up Minstrel")
        text("Checking the link...")
        background(state["bot"].status, after_status, lambda e: link_page(e, state["bot"].url))

    def after_status(info):
        state["info"] = info
        key_page(have_key=info.get("hasKey"))

    # 2. The key
    def key_page(have_key=False, error=None):
        name = state["info"]["deviceName"]
        page("Your Spotify developer key")
        text(f"{name} plays through your own Spotify account. Spotify only allows that with a developer key "
             "you create yourself. It's free, takes about two minutes, and needs Spotify Premium.")
        text("1.  Open the Spotify developer page and log in with the Spotify account you'll play music from.\n"
             "2.  Accept the developer terms if asked, then create a Soloist API key.\n"
             "3.  Copy the key and paste it here.", pady=(0, 10))
        ttk.Button(frame, text="Open the Spotify developer page", command=lambda: webbrowser.open(KEY_PAGE)).pack(anchor="w", pady=(0, 12))
        row = ttk.Frame(frame)
        row.pack(fill="x")
        entry = ttk.Entry(row, show="•", font=("Segoe UI", 10))
        entry.pack(side="left", fill="x", expand=True)
        shown = tk.BooleanVar(value=False)
        ttk.Checkbutton(row, text="Show", variable=shown,
                        command=lambda: entry.config(show="" if shown.get() else "•")).pack(side="left", padx=(8, 0))
        err = text(error or "", "Error.TLabel", pady=(8, 0))
        buttons = ttk.Frame(frame)
        buttons.pack(fill="x", side="bottom")

        def save():
            key = entry.get().strip()
            if not key:
                err.config(text="Paste your key first.")
                return
            err.config(text="Saving the key and starting your device...", style="Body.TLabel")
            save_btn.state(["disabled"])
            background(lambda: state["bot"].set_key(key), lambda info: after_key(info),
                       lambda e: key_page(have_key, e))

        save_btn = ttk.Button(buttons, text="Save key", command=save)
        save_btn.pack(side="right")
        if have_key:
            ttk.Button(buttons, text="Keep my current key", command=lambda: after_key(state["info"])).pack(side="right", padx=(0, 8))
        entry.focus()

    def after_key(info):
        # Already linked: Spotify reaches a paired device over the internet, so there's nothing to relay.
        if info.get("loggedIn"):
            already_page()
        else:
            pair_page()

    def already_page():
        name = state["info"]["deviceName"]
        page("Already linked")
        text(f"{name} is already linked to a Spotify account, so you're set: join a voice channel in Discord "
             f"and pick {name} in Spotify.")
        text("To link a different Spotify account instead, choose Pair again.")
        buttons = ttk.Frame(frame)
        buttons.pack(fill="x", side="bottom")
        ttk.Button(buttons, text="Close", command=root.destroy).pack(side="right")
        ttk.Button(buttons, text="Pair again", command=pair_page).pack(side="right", padx=(0, 8))

    # 3. Pairing
    def pair_page():
        name = state["info"]["deviceName"]
        page(f"Pick {name} in Spotify")
        text(f"Open the Spotify app, open the devices list (the speaker icon next to the play controls) "
             f"and pick {name}.")
        text("The Spotify desktop app on this computer works, or your phone if it's on the same Wi-Fi. "
             "The web player can't do this step, but works fine once you're set up.")
        text("If Windows asks whether to allow network access, click Allow.", pady=(0, 14))
        status = text("Waiting for Spotify...", "Status.TLabel")
        hint = text("")
        started = time.time()

        def nudge():
            p = state["pairing"]
            if p and not p.found and not p.done.is_set() and time.time() - started > 75:
                hint.config(text="Not showing up? Make sure the device running Spotify isn't on a guest network or VPN, and that "
                                 "Windows allowed \"Minstrel Setup\" on your network (Windows Security → Firewall → "
                                 "Allow an app). Spotify can take a minute to refresh its device list.")
            elif p and not p.done.is_set():
                root.after(5000, nudge)

        def report(event, detail):
            def show():
                if event == "found":
                    status.config(text=f"Spotify found {name}. Pick it if you haven't yet.")
                    hint.config(text="")
                elif event == "login":
                    status.config(text="Spotify sent your login. Connecting...")
                elif event == "refused":
                    status.config(text=f"Spotify didn't accept the login ({detail}).", style="Error.TLabel")
                    hint.config(text="This usually means the developer key is wrong. Close this, run /pair again and "
                                     "enter the key again.")
                elif event == "paired":
                    done_page()
                elif event == "expired":
                    status.config(text="Timed out. Run /pair in Discord for a new link and try again.", style="Error.TLabel")
            ui(show)

        state["pairing"] = Pairing(state["bot"], name, report)
        threading.Thread(target=state["pairing"].run, daemon=True).start()
        root.after(5000, nudge)

    # 4. Done
    def done_page():
        name = state["info"]["deviceName"]
        page("All set!")
        text(f"{name} is linked to your Spotify. It now shows up in your devices list in any Spotify, "
             "web player included, from anywhere.")
        text(f"To play music for your table: join a voice channel in Discord, open Spotify and pick {name}. "
             "The bot joins your channel on its own (or use /join).")
        ttk.Button(frame, text="Close", command=root.destroy).pack(anchor="e", side="bottom")

    def on_close():
        if state["pairing"]:
            state["pairing"].stop()
        root.destroy()

    root.protocol("WM_DELETE_WINDOW", on_close)
    link = link or link_from_exe_name()
    if link:
        try:
            state["bot"] = Bot(link)
            check_link()
        except SetupError as e:
            link_page(str(e))
    else:
        link_page()
    pump()
    root.mainloop()
    return 0


def main():
    args = [a for a in sys.argv[1:] if a != "--cli"]
    link = args[0] if args else None
    if "--cli" not in sys.argv:
        try:
            import tkinter
            tkinter.Tk().destroy()  # fails without Tk or without a display
        except Exception:
            pass
        else:
            return run_gui(link)
    code = run_cli(link)
    if getattr(sys, "frozen", False):
        input("\nPress Enter to close.")
    return code


if __name__ == "__main__":
    sys.exit(main())
