#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Pak Otto Upload Server — biar Bos bisa upload (copy-paste) file dari lokal ke folder
pak_otto_image & pak_otto_video di server OpenClaw lewat browser.

- Port: 8124 (bind 0.0.0.0) → akses dari Mac Bos via Tailscale: http://100.79.230.61:8124
- Halaman: pilih folder (Image / Video), pilih file (multipart), upload
- Simpan: /home/mantapman/.hermes/profiles/atun/workspace/pak_otto_{image,video}/
- Proteksi: token sederhana (query ?t=... atau header) — ganti TOKEN sesuai keinginan
"""
import os, re, sys, html, uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs

ROOT = "/home/mantapman/.hermes/profiles/atun/workspace"
DIRS = {
    "image": os.path.join(ROOT, "pak_otto_image"),
    "video": os.path.join(ROOT, "pak_otto_video"),
}
TOKEN = "otto2026"  # ganti kalau mau

PAGE = """<!DOCTYPE html>
<html lang="id"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pak Otto Upload</title>
<style>
 body{font-family:system-ui,sans-serif;background:#1E3A8A;color:#fff;display:flex;justify-content:center;padding:40px 16px;margin:0}
 .card{background:#fff;color:#111;border-radius:16px;padding:28px;max-width:480px;width:100%;box-shadow:0 10px 30px rgba(0,0,0,.3)}
 h1{font-size:22px;margin:0 0 6px} p.sub{margin:0 0 18px;color:#555;font-size:14px}
 label{font-weight:600;font-size:14px} select,input[type=file]{width:100%;padding:10px;margin:8px 0 16px;border:1px solid #ccc;border-radius:8px;font-size:14px}
 input[type=file]{background:#f5f5f5}
 button{width:100%;padding:12px;background:#F97316;color:#fff;border:0;border-radius:8px;font-size:16px;font-weight:700;cursor:pointer}
 button:hover{background:#ea6a0b}
 .ok{background:#dcfce7;color:#166534;padding:10px;border-radius:8px;margin-top:14px;font-size:14px}
 .err{background:#fee2e2;color:#991b1b;padding:10px;border-radius:8px;margin-top:14px;font-size:14px}
 ul{font-size:13px;color:#444;padding-left:18px;line-height:1.6}
</style></head><body>
<div class="card">
 <h1>📁 Upload Aset Pak Otto</h1>
 <p class="sub">Pilih folder, pilih file, klik Upload. File langsung masuk server OpenClaw.</p>
 <form method="post" enctype="multipart/form-data" action="/upload">
  <label for="folder">Folder tujuan</label>
  <select name="folder" id="folder">
   <option value="image">🖼️ pak_otto_image</option>
   <option value="video">🎬 pak_otto_video</option>
  </select>
  <label for="file">File (boleh banyak sekaligus)</label>
  <input type="file" name="file" id="file" multiple required>
  <button type="submit">⬆️ Upload</button>
 </form>
 {MSG}
 <p class="sub" style="margin-top:18px">Setelah upload, file langsung bisa dipakai (URL server otomatis).</p>
</div></body></html>"""

class Handler(BaseHTTPRequestHandler):
    def log_message(self, *a):
        pass

    def _check_token(self):
        q = parse_qs(urlparse(self.path).query)
        t = q.get("t", [""])[0]
        if t == TOKEN:
            return True
        # header fallback
        if self.headers.get("X-Token") == TOKEN:
            return True
        return False

    def _send(self, code, body, ctype="text/html; charset=utf-8"):
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if not self._check_token():
            self._send(401, "<h3>401 — butuh token. Akses: http://IP:8124/?t=otto2026</h3>".encode())
            return
        msg = ""
        if os.environ.get("UPLOAD_MSG"):
            msg = os.environ.pop("UPLOAD_MSG")
        self._send(200, PAGE.replace("{MSG}", msg).encode())

    def do_POST(self):
        if not self._check_token():
            self._send(401, "<h3>401 — token salah</h3>".encode())
            return
        ctype = self.headers.get("Content-Type", "")
        if "multipart/form-data" not in ctype:
            self._send(400, "<h3>400 — butuh multipart/form-data</h3>".encode())
            return
        try:
            length = int(self.headers.get("Content-Length", 0))
        except ValueError:
            length = 0
        body = self.rfile.read(length)
        boundary = ctype.split("boundary=")[1].strip().strip('"').encode()
        parts = body.split(b"--" + boundary)
        folder = "image"
        saved = []
        errors = []
        for part in parts:
            if not part or part in (b"\r\n", b"--\r\n", b"--"):
                continue
            head, _, data = part.partition(b"\r\n\r\n")
            data = data.rstrip(b"\r\n")
            head_txt = head.decode("utf-8", "ignore")
            m = re.search(r'name="([^"]+)"', head_txt)
            if not m:
                continue
            name = m.group(1)
            if name == "folder":
                folder = data.decode().strip()
                if folder not in DIRS:
                    folder = "image"
                continue
            if name == "file":
                fm = re.search(r'filename="([^"]*)"', head_txt)
                fname = fm.group(1) if fm else ""
                fname = os.path.basename(fname.replace("\\", "/"))
                if not fname or not data:
                    continue
                safe = re.sub(r"[^A-Za-z0-9._-]", "_", fname)
                dest = os.path.join(DIRS[folder], safe)
                with open(dest, "wb") as f:
                    f.write(data)
                saved.append(safe)
        if saved:
            msg = f'<div class="ok">✅ {len(saved)} file terupload ke pak_otto_{folder}/:<br>' + "<br>".join(html.escape(s) for s in saved) + "</div>"
        else:
            msg = '<div class="err">⚠️ Tidak ada file tersimpan. Coba lagi.</div>'
        os.environ["UPLOAD_MSG"] = msg
        self.send_response(303)
        self.send_header("Location", "/?t=" + TOKEN)
        self.end_headers()

if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8124
    for d in DIRS.values():
        os.makedirs(d, exist_ok=True)
    srv = ThreadingHTTPServer(("0.0.0.0", port), Handler)
    print(f"Pak Otto Upload Server jalan di port {port}")
    print(f"Folder: {DIRS['image']} & {DIRS['video']}")
    print(f"Akses: http://100.79.230.61:{port}/?t={TOKEN}")
    srv.serve_forever()
