#!/usr/bin/env python3
"""Drawing Board — Mike's markup surface for the wind-sculpture drawings.

He opens a drawing, marks it up with basic drawing tools, types what he wants
changed, and saves. The save writes two files into the project:

    output/markup/<drawing>-markup-<stamp>.png    the drawing with his marks on it
    output/markup/<drawing>-markup-<stamp>.json   the marks as data + his notes

The JSON is the part the render workers read: marks carry their coordinates in
IMAGE space, so a mark points at the same place whatever size the picture is.

Password: reuses the book manager's auth file, so there is one password per host.

    python3 app/server.py            # serves on 0.0.0.0:8082
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import json
import os
import pathlib
import re
import secrets
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import unquote, urlparse

HERE = pathlib.Path(__file__).resolve().parent
PROJECT = HERE.parent
OUTPUT = PROJECT / "output"
UPLOADS = OUTPUT / "uploads"
MARKUP = OUTPUT / "markup"
PAGE = HERE / "index.html"
MANUAL = HERE / "MANUAL.md"
PEOPLE = HERE / "people.json"

# the host's existing password seeds the owner on first run — one password per host
AUTH_FILE = pathlib.Path(os.environ.get("DRAWING_BOARD_AUTH", "/home/mike/bookapp/auth.json"))
PORT = int(os.environ.get("DRAWING_BOARD_PORT", "8082"))
HOST = os.environ.get("DRAWING_BOARD_HOST", "0.0.0.0")
REALM = "Slow Bloom"

# only ever touch a plain image file name — no paths, no traversal
SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,120}\.(png|jpg|jpeg|webp)$", re.I)
MIME = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}
MAX_BODY = 48 * 1024 * 1024
MAX_IMAGE = 24 * 1024 * 1024

# words for shareable passwords: spoken one-handed over a phone without spelling
WORDS = ("alder amber aspen basalt birch cedar clover copper cotton ember fern flint "
         "granite hazel heather indigo juniper larch lilac linen maple marble mesquite "
         "mulberry nettle oak onyx pebble pinyon quartz reed ridge sable sage sorrel "
         "spruce stone sumac tamarack thistle timber willow yarrow").split()


def _hash(pw: str, salt: str) -> str:
    return hashlib.pbkdf2_hmac("sha256", pw.encode("utf-8"), bytes.fromhex(salt), 200_000).hex()


def load_people() -> list[dict]:
    try:
        return json.loads(PEOPLE.read_text()).get("people", [])
    except Exception:
        return []


def save_people(people: list[dict]) -> None:
    PEOPLE.write_text(json.dumps({"people": people}, indent=2))
    try:
        PEOPLE.chmod(0o600)
    except Exception:
        pass


def make_password() -> str:
    return "-".join(secrets.choice(WORDS) for _ in range(4)).title() + "-" + str(secrets.randbelow(90) + 10)


def seed_people() -> None:
    """First run: the owner is whoever the host's password already belongs to."""
    if PEOPLE.exists():
        return
    cfg = json.loads(AUTH_FILE.read_text())
    salt = os.urandom(16).hex()
    save_people([{"name": cfg["username"], "role": "owner", "salt": salt,
                  "hash": _hash(cfg["password"], salt), "added": time.strftime("%Y-%m-%d")}])
    print(f"  seeded people.json from {AUTH_FILE.name} — {cfg['username']} is the owner")


def identify(user: str, pw: str) -> dict | None:
    """Who is this? Constant-time, and never hints at which field was wrong."""
    found = None
    for p in load_people():
        name_ok = hmac.compare_digest(user, p.get("name", ""))
        hash_ok = hmac.compare_digest(_hash(pw, p.get("salt", "00" * 16)), p.get("hash", ""))
        if name_ok and hash_ok:
            found = p
    return found


def image_list() -> list[dict]:
    """Everything he could mark up: rendered drawings, and anything imported."""
    out = []
    for base, kind in ((OUTPUT, "drawing"), (UPLOADS, "imported")):
        if not base.is_dir():
            continue
        for p in sorted(base.glob("*")):
            if p.suffix.lower() not in MIME:
                continue
            st = p.stat()
            out.append({
                "name": p.name,
                "kind": kind,
                "url": f"/img/{p.name}" if kind == "drawing" else f"/uploads/{p.name}",
                "bytes": st.st_size,
                "modified": time.strftime("%Y-%m-%d %H:%M", time.localtime(st.st_mtime)),
                "sessions": sum(1 for q in MARKUP.glob(f"{p.stem}-markup-*.json")) if MARKUP.is_dir() else 0,
            })
    return out


def sessions() -> list[dict]:
    if not MARKUP.is_dir():
        return []
    out = []
    for j in sorted(MARKUP.glob("*-markup-*.json"), reverse=True):
        try:
            d = json.loads(j.read_text())
        except Exception:
            continue
        png = j.with_suffix(".png")
        out.append({
            "id": j.stem,
            "drawing": d.get("drawing", "?"),
            "when": d.get("saved_local", "?"),
            "by": d.get("saved_by", "?"),
            "marks": len(d.get("marks", [])),
            "notes": (d.get("notes") or "")[:400],
            "png": png.name if png.exists() else None,
        })
    return out[:40]


class Handler(BaseHTTPRequestHandler):
    server_version = "DrawingBoard/1.0"

    # ── helpers ──
    def _who(self) -> dict | None:
        """Which person is this? None means the door stays shut."""
        header = self.headers.get("Authorization", "")
        if not header.startswith("Basic "):
            return None
        try:
            user, _, pw = base64.b64decode(header[6:]).decode().partition(":")
        except Exception:
            return None
        return identify(user, pw)

    def _deny(self):
        body = b"Authentication required."
        self.send_response(401)
        self.send_header("WWW-Authenticate", f'Basic realm="{REALM}"')
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def _send(self, code: int, body: bytes, ctype: str = "text/plain; charset=utf-8"):
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def _json(self, obj, code: int = 200):
        self._send(code, json.dumps(obj, indent=2).encode(), "application/json; charset=utf-8")

    def log_message(self, format, *args):
        print(f"  {self.address_string()}  {format % args}", flush=True)

    # ── routes ──
    def do_GET(self):
        path = unquote(urlparse(self.path).path)
        who = self._who()
        if not who:
            return self._deny()

        if path in ("/", "/index.html"):
            if not PAGE.exists():
                return self._send(500, b"index.html is missing next to server.py")
            return self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8")

        if path == "/help":
            body = MANUAL.read_bytes() if MANUAL.exists() else b"no MANUAL.md next to server.py"
            return self._send(200, body, "text/plain; charset=utf-8")

        if path == "/api/drawings":
            return self._json({"drawings": image_list(),
                               "you": {"name": who["name"], "role": who.get("role", "guest")}})
        if path == "/api/sessions":
            return self._json({"sessions": sessions()})
        if path == "/api/people":
            if who.get("role") != "owner":
                return self._json({"ok": False, "error": "only the owner sees the list"}, 403)
            return self._json({"people": [{"name": p["name"], "role": p.get("role", "guest"),
                                           "added": p.get("added")} for p in load_people()]})

        if path.startswith("/img/"):
            return self._serve_image(OUTPUT, path[5:])
        if path.startswith("/uploads/"):
            return self._serve_image(UPLOADS, path[9:])
        if path.startswith("/markup/"):
            return self._serve_image(MARKUP, path[8:])

        self._send(404, b"not found")

    def _serve_image(self, base: pathlib.Path, name: str):
        name = name.strip()
        if not SAFE_NAME.match(name):
            return self._send(400, b"bad drawing name")
        p = (base / name).resolve()
        try:
            p.relative_to(base.resolve())
        except ValueError:
            return self._send(400, b"bad path")
        if not p.is_file():
            return self._send(404, b"no such drawing")
        return self._send(200, p.read_bytes(), MIME.get(p.suffix.lower(), "application/octet-stream"))

    def _read_body(self):
        n = int(self.headers.get("Content-Length") or 0)
        if n <= 0 or n > MAX_BODY:
            self._json({"ok": False, "error": "bad body size"}, 413)
            return None
        try:
            return json.loads(self.rfile.read(n).decode())
        except Exception as e:
            self._json({"ok": False, "error": f"bad json: {e}"}, 400)
            return None

    def _upload(self, payload, who):
        """Import his own picture — a site photo, a sketch, a reference — to mark up."""
        data = str(payload.get("data") or "")
        if not data.startswith("data:image/"):
            return self._json({"ok": False, "error": "that was not an image"}, 400)
        try:
            raw = base64.b64decode(data.split(",", 1)[1])
        except Exception as e:
            return self._json({"ok": False, "error": f"could not decode that: {e}"}, 400)
        if len(raw) > MAX_IMAGE:
            return self._json({"ok": False, "error": "image is larger than 24 MB"}, 413)
        ext = ".png" if "png" in data[:30].lower() else ".jpg"
        caption = " ".join(str(payload.get("caption") or "").split())[:160]
        label = re.sub(r"[^A-Za-z0-9]+", "-", caption).strip("-").lower()[:44]
        name = f"{time.strftime('%Y%m%d-%H%M%S')}-{label or 'imported'}{ext}"
        UPLOADS.mkdir(parents=True, exist_ok=True)
        (UPLOADS / name).write_bytes(raw)
        (UPLOADS / f"{pathlib.Path(name).stem}.txt").write_text(
            f"imported by {who['name']} on {time.strftime('%Y-%m-%d %H:%M')}\n"
            f"caption: {caption or '(none)'}\n", encoding="utf-8")
        return self._json({"ok": True, "name": name, "bytes": len(raw), "caption": caption})

    def _add_person(self, payload, who):
        if who.get("role") != "owner":
            return self._json({"ok": False, "error": "only the owner can add people"}, 403)
        name = " ".join(str(payload.get("name") or "").split())[:40]
        if len(name) < 2:
            return self._json({"ok": False, "error": "give them a name"}, 400)
        people = load_people()
        if any(p["name"].lower() == name.lower() for p in people):
            return self._json({"ok": False, "error": "that name is already on the list"}, 400)
        pw = make_password()
        salt = os.urandom(16).hex()
        people.append({"name": name, "role": "guest", "salt": salt,
                       "hash": _hash(pw, salt), "added": time.strftime("%Y-%m-%d")})
        save_people(people)
        return self._json({
            "ok": True, "name": name, "password": pw,
            "invite": (f"{name} — you can look at and mark up the sculpture drawings here.\n\n"
                       f"  On the home network:   http://10.0.0.177:8082\n"
                       f"  Away from home:        http://100.101.221.93:8082   (needs Tailscale)\n\n"
                       f"  username:  {name}\n  password:  {pw}\n\n"
                       "Pick a drawing, or import a picture of your own. Draw on it with the tools, "
                       "type any comments in the box, then press \"Save my changes\". "
                       "Everything you mark comes back to me.\n")})

    def _remove_person(self, payload, who):
        if who.get("role") != "owner":
            return self._json({"ok": False, "error": "only the owner can remove people"}, 403)
        name = " ".join(str(payload.get("name") or "").split())
        if name.lower() == who["name"].lower():
            return self._json({"ok": False, "error": "you cannot remove yourself"}, 400)
        people = load_people()
        left = [p for p in people if p["name"].lower() != name.lower()]
        if len(left) == len(people):
            return self._json({"ok": False, "error": "no such person"}, 404)
        save_people(left)
        return self._json({"ok": True, "removed": name, "left": len(left)})

    def do_POST(self):
        path = unquote(urlparse(self.path).path)
        who = self._who()
        if not who:
            return self._deny()
        payload = self._read_body()
        if payload is None:
            return
        if path == "/api/upload":
            return self._upload(payload, who)
        if path == "/api/people":
            return self._add_person(payload, who)
        if path == "/api/people/remove":
            return self._remove_person(payload, who)
        if path != "/api/save":
            return self._send(404, b"not found")

        drawing = str(payload.get("drawing") or "").strip()
        if not SAFE_NAME.match(drawing):
            return self._json({"ok": False, "error": "bad drawing name"}, 400)

        stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
        stem = pathlib.Path(drawing).stem
        MARKUP.mkdir(parents=True, exist_ok=True)

        composite = payload.get("composite") or ""
        png_path = MARKUP / f"{stem}-markup-{stamp}.png"
        wrote_png = False
        if composite.startswith("data:image/png;base64,"):
            raw = base64.b64decode(composite.split(",", 1)[1])
            png_path.write_bytes(raw)
            wrote_png = True
        elif composite:
            return self._json({"ok": False, "error": "composite was not a PNG data URL"}, 400)

        marks = payload.get("marks") or []
        record = {
            "drawing": drawing,
            "drawing_size": payload.get("drawing_size"),
            "saved_local": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            "saved_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "notes": payload.get("notes") or "",
            "mark_count": len(marks),
            # marks are in IMAGE coordinates so they line up at any display size
            "marks": marks,
            "composite": png_path.name if wrote_png else None,
            "saved_by": f"{who['name']}, via the drawing board",
        }
        (MARKUP / f"{stem}-markup-{stamp}.json").write_text(json.dumps(record, indent=2))

        idx = MARKUP / "index.json"
        try:
            hist = json.loads(idx.read_text()) if idx.exists() else []
        except Exception:
            hist = []
        hist.insert(0, {
            "id": f"{stem}-markup-{stamp}",
            "drawing": drawing,
            "when": record["saved_local"],
            "marks": len(marks),
            "notes": record["notes"][:200],
            "png": record["composite"],
        })
        idx.write_text(json.dumps(hist[:200], indent=2))

        return self._json({
            "ok": True,
            "saved": [str(png_path.relative_to(PROJECT)) if wrote_png else None,
                      str((MARKUP / f'{stem}-markup-{stamp}.json').relative_to(PROJECT))],
            "marks": len(marks),
            "notes_chars": len(record["notes"]),
            "when": record["saved_local"],
        })


def main() -> None:
    if not AUTH_FILE.exists() and not PEOPLE.exists():
        print(f"  !! no people.json and no auth file at {AUTH_FILE} — refusing to serve without a password")
        raise SystemExit(1)
    seed_people()
    MARKUP.mkdir(parents=True, exist_ok=True)
    UPLOADS.mkdir(parents=True, exist_ok=True)
    n = len(load_people())
    print(f"  drawing board on http://{HOST}:{PORT}  ({n} account{'s' if n != 1 else ''}, password required)")
    print(f"  drawings from {OUTPUT} and {UPLOADS}")
    print(f"  markup saved to {MARKUP}")
    ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()


if __name__ == "__main__":
    main()
