#!/usr/bin/env python3
"""Mini HTTP server for Keith DM audit. Serves HTML + tracks activity."""

import json, os
from datetime import datetime
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from urllib.parse import urlparse

BASE     = Path(__file__).parent
LOG_FILE = BASE / "activity_log.json"
PORT     = 8765

def load_log():
    if LOG_FILE.exists():
        with open(LOG_FILE) as f:
            return json.load(f)
    return []

def save_log(log):
    with open(LOG_FILE, "w") as f:
        json.dump(log, f, indent=2)

class Handler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(BASE), **kwargs)

    def log_message(self, format, *args):
        pass  # suppress access logs

    def do_POST(self):
        if self.path == "/track":
            length = int(self.headers.get("Content-Length", 0))
            body   = self.rfile.read(length)
            try:
                data = json.loads(body)
                log  = load_log()
                log.append({
                    "ts":         datetime.now().strftime("%Y-%m-%d %H:%M"),
                    "handle":     data.get("handle", ""),
                    "name":       data.get("name", ""),
                    "type":       data.get("type", ""),
                    "suggestion": data.get("suggestion", ""),
                    "dm_url":     data.get("dm_url", ""),
                })
                save_log(log)
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Access-Control-Allow-Origin", "*")
                self.end_headers()
                self.wfile.write(b'{"ok":true}')
            except Exception as e:
                self.send_response(500)
                self.end_headers()
        elif self.path == "/untrack":
            length = int(self.headers.get("Content-Length", 0))
            body   = self.rfile.read(length)
            try:
                data   = json.loads(body)
                handle = data.get("handle", "")
                log    = load_log()
                # remove the most recent entry for this handle (single-step undo)
                for i in range(len(log) - 1, -1, -1):
                    if log[i].get("handle") == handle:
                        del log[i]
                        break
                save_log(log)
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Access-Control-Allow-Origin", "*")
                self.end_headers()
                self.wfile.write(b'{"ok":true}')
            except Exception:
                self.send_response(500)
                self.end_headers()
        else:
            self.send_response(404)
            self.end_headers()

    def do_GET(self):
        if self.path == "/log" or self.path == "/log/":
            self._serve_log()
        elif self.path == "/log.json":
            self._serve_log_json()
        else:
            super().do_GET()

    def _serve_log_json(self):
        log = load_log()
        handles = sorted({e["handle"] for e in log if e.get("handle")})
        body = json.dumps(handles).encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "Content-Type")
        self.end_headers()

    def _serve_log(self):
        log  = load_log()
        today = datetime.now().strftime("%Y-%m-%d")
        today_entries = [e for e in log if e["ts"].startswith(today)]
        all_entries   = list(reversed(log))

        def row(e, dim=False):
            style = "opacity:.45;" if dim else ""
            badge_color = "#ff3b30" if e["type"] == "NEEDS_REPLY" else "#ff9500"
            return f"""<tr style="{style}">
              <td>{e['ts']}</td>
              <td><a href="https://instagram.com/{e['handle'].lstrip('@')}/" target="_blank" style="color:#5bf;text-decoration:none">{e['handle']}</a></td>
              <td><span style="background:{badge_color};color:#fff;padding:2px 7px;border-radius:4px;font-size:11px">{e['type']}</span></td>
              <td style="color:#ffd60a;font-size:12px">{e['suggestion'][:120]}{'…' if len(e['suggestion'])>120 else ''}</td>
            </tr>"""

        rows_today = "".join(row(e) for e in today_entries) or "<tr><td colspan=4 style='color:#555;padding:20px'>nothing yet today</td></tr>"
        rows_all   = "".join(row(e, dim=(not e["ts"].startswith(today))) for e in all_entries[:100])

        html = f"""<!DOCTYPE html>
<html><head><meta charset="UTF-8">
<title>Keith DM Activity Log</title>
<style>
*{{box-sizing:border-box;margin:0;padding:0}}
body{{font-family:-apple-system,sans-serif;background:#0c0c0e;color:#e0e0e0;font-size:13px;padding:24px}}
h1{{font-size:16px;color:#fff;margin-bottom:4px}}
h2{{font-size:13px;color:#666;margin:20px 0 8px;text-transform:uppercase;letter-spacing:.05em}}
.count{{color:#888;font-size:12px;margin-bottom:16px}}
table{{width:100%;border-collapse:collapse;margin-bottom:32px}}
th{{color:#555;font-size:10px;text-transform:uppercase;letter-spacing:.06em;padding:6px 10px;text-align:left;border-bottom:1px solid #222}}
td{{padding:9px 10px;border-bottom:1px solid #161618;vertical-align:top}}
a.back{{color:#f90;text-decoration:none;font-size:12px;display:inline-block;margin-bottom:16px}}
</style></head>
<body>
<a href="/network_audit.html" class="back">← back to audit</a>
<h1>Activity Log</h1>

<h2>today — {today}</h2>
<p class="count">{len(today_entries)} DMs opened</p>
<table>
<thead><tr><th>time</th><th>handle</th><th>type</th><th>suggestion sent</th></tr></thead>
<tbody>{rows_today}</tbody>
</table>

<h2>all time</h2>
<p class="count">{len(log)} total</p>
<table>
<thead><tr><th>time</th><th>handle</th><th>type</th><th>suggestion sent</th></tr></thead>
<tbody>{rows_all}</tbody>
</table>
</body></html>"""

        encoded = html.encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(encoded)))
        self.end_headers()
        self.wfile.write(encoded)

if __name__ == "__main__":
    os.chdir(BASE)
    print(f"serving on http://localhost:{PORT}")
    print(f"audit:    http://localhost:{PORT}/network_audit.html")
    print(f"log:      http://localhost:{PORT}/log")
    HTTPServer(("", PORT), Handler).serve_forever()
