#!/usr/bin/env python3
"""
TalkPulse PowerPoint sync (Windows).

Watches PowerPoint on this laptop and reports every slide change to your
TalkPulse session, so slide numbers show up in the event log automatically.

One-time setup:   pip install pywin32
Download this script from the TalkPulse presenter page ("personal sync script").
That copy already knows your TalkPulse address and your personal token, so from
then on just start it - before or during the talk, no arguments, no copying:

    python powerpoint_sync.py

It always reports to your most recent TalkPulse session. You can leave it
running between talks.

Slide numbers are the real positions in the file, i.e. what you see in the
editor's slide panel (hidden slides are counted). Works in slide show mode and,
as a fallback, in normal editing view.

Overlay: two small always-on-top windows open next to the sync:
  * "TalkPulse" window with the live pie chart (drag it to YOUR screen).
  * QR code window, hidden at first. Press the "Show QR" button (or key Q) in the
    TalkPulse window to show it; drag it onto the projector screen, e.g. a corner
    of your slide. Double-click the QR code (or press the button) to hide it again.

Options:  --no-overlay   sync only, no windows
          --demo   send fake slide numbers (test without PowerPoint)
          --url / --token   override the built-in address / token
          --code / --key    old-style: talk to one specific session
"""
import argparse
import base64
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
import urllib.parse

# Filled in by the TalkPulse server when you download the personal copy.
DEFAULT_URL = None
DEFAULT_TOKEN = None

HEARTBEAT_SECONDS = 5  # re-send the current slide this often, so new sessions are picked up


def post_slide(base_url, payload):
    """Send the current slide to the server. Returns the parsed JSON reply."""
    body = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        base_url.rstrip("/") + "/api/slide",
        data=body,
        headers={"Content-Type": "application/json", "User-Agent": "talkpulse-powerpoint-sync/2.0"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=20) as resp:
        return json.loads(resp.read().decode("utf-8"))


def read_current_slide(app):
    """Return (slide_number, title) from a PowerPoint COM application, or None."""
    slide = None
    try:
        if app.SlideShowWindows.Count > 0:
            slide = app.SlideShowWindows(1).View.Slide
    except Exception:
        slide = None
    if slide is None:
        try:
            slide = app.ActiveWindow.View.Slide  # editing view
        except Exception:
            return None
    try:
        number = int(slide.SlideIndex)
    except Exception:
        return None
    title = ""
    try:
        if slide.Shapes.HasTitle:
            title = str(slide.Shapes.Title.TextFrame.TextRange.Text).strip()
    except Exception:
        title = ""
    return number, title


def connect_powerpoint():
    try:
        import win32com.client  # type: ignore
    except ImportError:
        die("pywin32 is missing. Install it with:  pip install pywin32")
    try:
        return win32com.client.GetActiveObject("PowerPoint.Application")
    except Exception:
        return None


def demo_provider():
    state = {"n": 0, "last": 0.0}

    def read():
        now = time.time()
        if now - state["last"] > 4:
            state["n"] = state["n"] % 5 + 1
            state["last"] = now
        return state["n"], "Demo slide %d" % state["n"]

    return read


def die(msg):
    """Exit the whole program, also when called from the sync thread."""
    print(msg)
    sys.stdout.flush()
    os._exit(1)


def fetch_json(url, timeout=10):
    req = urllib.request.Request(url, headers={"User-Agent": "talkpulse-powerpoint-sync/2.0"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return json.loads(resp.read().decode("utf-8"))


def run_overlay(base_url, token, show_qr=False):
    """Pie chart window + toggleable QR window (tkinter). Returns False if tkinter is unavailable."""
    try:
        import tkinter as tk
    except ImportError:
        return False

    state = {"data": None, "qr_code": None, "qr_b64": None, "stop": False}
    base = base_url.rstrip("/")

    def poll():
        while not state["stop"]:
            try:
                d = fetch_json(base + "/api/overlay?token=" + urllib.parse.quote(token))
                state["data"] = d if d.get("active") else None
                if d.get("active") and d.get("code") != state["qr_code"]:
                    q = fetch_json(base + "/api/qr/" + urllib.parse.quote(d["code"]))
                    state["qr_b64"] = q["dataUrl"].split(",", 1)[1]
                    state["qr_code"] = d["code"]
            except Exception:
                pass
            time.sleep(1.5)

    threading.Thread(target=poll, daemon=True).start()

    root = tk.Tk()
    root.title("TalkPulse")
    root.attributes("-topmost", True)
    root.geometry("260x360+60+60")
    root.configure(bg="#ffffff")
    canvas = tk.Canvas(root, width=240, height=240, bg="#ffffff", highlightthickness=0)
    canvas.pack(pady=(10, 0))
    info = tk.Label(root, text="", bg="#ffffff", font=("Segoe UI", 11), fg="#222222")
    info.pack(pady=(4, 0))
    btn = tk.Button(root, text="Show QR (Q)", font=("Segoe UI", 10))
    btn.pack(pady=8)

    qr = tk.Toplevel(root)
    qr.withdraw()
    qr.overrideredirect(True)
    qr.attributes("-topmost", True)
    qr.configure(bg="#ffffff", highlightbackground="#222222", highlightthickness=2)
    qr_img_label = tk.Label(qr, bg="#ffffff")
    qr_img_label.pack(padx=8, pady=(8, 0))
    qr_text = tk.Label(qr, text="", bg="#ffffff", font=("Segoe UI", 20, "bold"), fg="#111111")
    qr_text.pack(pady=(0, 8))
    qr_state = {"visible": False, "photo": None, "shown_code": None, "drag": None}

    def place_qr_default():
        qr.update_idletasks()
        w, h = qr.winfo_reqwidth(), qr.winfo_reqheight()
        qr.geometry("+%d+%d" % (root.winfo_screenwidth() - w - 40, root.winfo_screenheight() - h - 80))

    def toggle_qr(_event=None):
        if qr_state["visible"]:
            qr.withdraw()
            qr_state["visible"] = False
            btn.config(text="Show QR (Q)")
        else:
            if qr_state["photo"] is None:
                return
            if not qr_state["shown_code"] or not qr.winfo_ismapped():
                place_qr_default()
            qr.deiconify()
            qr.lift()
            qr.attributes("-topmost", True)
            qr_state["visible"] = True
            btn.config(text="Hide QR (Q)")

    def start_drag(e):
        qr_state["drag"] = (e.x_root - qr.winfo_x(), e.y_root - qr.winfo_y())

    def do_drag(e):
        d = qr_state["drag"]
        if d:
            qr.geometry("+%d+%d" % (e.x_root - d[0], e.y_root - d[1]))

    for w in (qr, qr_img_label, qr_text):
        w.bind("<ButtonPress-1>", start_drag)
        w.bind("<B1-Motion>", do_drag)
        w.bind("<Double-Button-1>", toggle_qr)
    btn.config(command=toggle_qr)
    root.bind("<q>", toggle_qr)
    root.bind("<Q>", toggle_qr)

    def draw_pie(d):
        canvas.delete("all")
        box = (20, 20, 220, 220)
        if not d or d["total"] == 0:
            canvas.create_oval(*box, fill="#e5e5e5", outline="")
            return
        frac_out = d["outCount"] / float(d["total"])
        if frac_out <= 0:
            canvas.create_oval(*box, fill="#1f9d6e", outline="")
        elif frac_out >= 1:
            canvas.create_oval(*box, fill="#d64545", outline="")
        else:
            canvas.create_arc(*box, start=90, extent=-360 * frac_out, fill="#d64545", outline="#ffffff", width=2)
            canvas.create_arc(*box, start=90 - 360 * frac_out, extent=-360 * (1 - frac_out),
                              fill="#1f9d6e", outline="#ffffff", width=2)

    def tick():
        d = state["data"]
        draw_pie(d)
        if d is None:
            info.config(text="No session yet")
        else:
            phase = {"lobby": "lobby", "live": "live", "ended": "ended"}.get(d["phase"], "")
            slide = ("   Slide %s" % d["slide"]) if d.get("slide") else ""
            info.config(text="%d in  /  %d out   (%s)%s" % (d["inCount"], d["outCount"], phase, slide))
        if state["qr_b64"] and state["qr_code"] != qr_state["shown_code"]:
            try:
                qr_state["photo"] = tk.PhotoImage(data=state["qr_b64"])
                qr_state["photo"] = qr_state["photo"].subsample(2, 2) if qr_state["photo"].width() >= 360 else qr_state["photo"]
                qr_img_label.config(image=qr_state["photo"])
                qr_text.config(text=state["qr_code"])
                qr_state["shown_code"] = state["qr_code"]
            except Exception:
                pass
        root.after(400, tick)

    def maybe_show_qr():
        if show_qr and qr_state["photo"] is not None and not qr_state["visible"] and not qr_state.get("auto"):
            qr_state["auto"] = True
            toggle_qr()
        root.after(500, maybe_show_qr)

    def on_close():
        state["stop"] = True
        root.destroy()
        os._exit(0)

    root.protocol("WM_DELETE_WINDOW", on_close)
    tick()
    maybe_show_qr()
    try:
        root.mainloop()
    except KeyboardInterrupt:
        pass
    return True


def main():
    ap = argparse.ArgumentParser(description="Report PowerPoint slide changes to TalkPulse.")
    ap.add_argument("--url", default=DEFAULT_URL, help="TalkPulse address, e.g. https://your-app.onrender.com")
    ap.add_argument("--token", default=DEFAULT_TOKEN, help="your personal presenter token")
    ap.add_argument("--code", help="session code (old-style, instead of --token)")
    ap.add_argument("--key", help="presenter key (old-style, instead of --token)")
    ap.add_argument("--interval", type=float, default=0.5, help="seconds between checks (default 0.5)")
    ap.add_argument("--demo", action="store_true", help="send fake slide numbers (to test without PowerPoint)")
    ap.add_argument("--show-qr", action="store_true", help="show the QR window right away")
    ap.add_argument("--no-overlay", action="store_true", help="sync only, do not open the pie chart / QR windows")
    args = ap.parse_args()

    if not args.url:
        sys.exit("No TalkPulse address known. Download the personal script from the presenter page, or add --url https://...")
    if args.code and args.key:
        ident = {"code": args.code, "key": args.key}
    elif args.token:
        ident = {"token": args.token}
    else:
        sys.exit("No token known. Download the personal script from the presenter page (it has your token built in).")

    if not args.no_overlay and args.token and not (args.code and args.key):
        t = threading.Thread(target=sync_loop, args=(args, ident), daemon=True)
        t.start()
        try:
            if run_overlay(args.url, args.token, args.show_qr):
                return
        except Exception as e:
            print("Overlay could not start (%s). Continuing with sync only." % e)
        else:
            print("Overlay not available (tkinter missing). Continuing with sync only.")
        try:
            while t.is_alive():
                time.sleep(0.5)
        except KeyboardInterrupt:
            print("\nStopped.")
        return
    sync_loop(args, ident)


def sync_loop(args, ident):
    app = None
    read = demo_provider() if args.demo else None
    last = None
    last_printed = None
    last_sent_at = 0.0
    connected_code = None
    warned_ppt = False
    warned_idle = False
    print("TalkPulse PowerPoint sync running (%s). Press Ctrl+C to stop." % args.url)
    if args.demo:
        print("Demo mode: sending fake slide numbers 1-5.")

    while True:
        try:
            if read is None:
                if app is None:
                    app = connect_powerpoint()
                if app is None:
                    if not warned_ppt:
                        print("Waiting for PowerPoint to be open...")
                        warned_ppt = True
                    time.sleep(2)
                    continue
                warned_ppt = False
                current = read_current_slide(app)
            else:
                current = read()

            due = current is not None and (current != last or time.time() - last_sent_at >= HEARTBEAT_SECONDS)
            if due:
                number, title = current
                payload = dict(ident, slide=str(number), title=title)
                try:
                    reply = post_slide(args.url, payload)
                except urllib.error.HTTPError as e:
                    if e.code == 404:
                        die("Unknown session code. Check --code (or use the personal script without --code).")
                    if e.code == 403:
                        die("Wrong token/key. Download the personal script from the presenter page again.")
                    print("Server answered HTTP %d - will retry." % e.code)
                    time.sleep(3)
                    continue
                except (urllib.error.URLError, TimeoutError, OSError) as e:
                    print("Could not reach the server (%s) - will retry." % e)
                    time.sleep(3)
                    continue
                last_sent_at = time.time()
                if not reply.get("active", True):
                    if not warned_idle:
                        if reply.get("phase") == "ended":
                            print("Your session has ended - waiting for the next one (start it on the presenter page).")
                        else:
                            print("No TalkPulse session yet - start one on the presenter page. Waiting...")
                        warned_idle = True
                    last = current  # re-check on the heartbeat, not every half second
                else:
                    warned_idle = False
                    if reply.get("code") != connected_code:
                        connected_code = reply.get("code")
                        last_printed = None
                        print("Connected to session %s." % connected_code)
                    if current != last_printed:
                        print("Slide %s%s" % (number, (" - " + title) if title else ""))
                        last_printed = current
                    last = current
            time.sleep(args.interval)
        except KeyboardInterrupt:
            print("\nStopped.")
            return
        except Exception as e:  # PowerPoint closed or COM hiccup: reconnect on next round
            app = None
            print("PowerPoint connection lost (%s). Reconnecting..." % e)
            time.sleep(2)


if __name__ == "__main__":
    main()
