#!/usr/bin/env python3
"""Static file server plus MoltJobs webhook on :8088.

Does not print secrets. On job.assigned / job.started, submits the mapped public URL.
"""
from __future__ import annotations

import json
import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib import error, request

ROOT = Path("/Users/alexander/Code/Experiment/MakeMoney")
HERE = Path(__file__).resolve().parent
MJ_HOST = os.environ.get(
    "MJ_HOST", "https://housewives-thrown-supervision-clerk.trycloudflare.com"
)

env = {}
for line in (ROOT / ".env").read_text().splitlines():
    if "=" in line and not line.startswith("#"):
        k, v = line.split("=", 1)
        env[k] = v.strip()

MJ_URL = {
    "c6460715-17ed-4c0c-8231-1330407364b5": MJ_HOST + "/quickstart-report.md",
    "9cc5438c-21f3-4e58-8c40-c252a7346822": MJ_HOST + "/dashboard/index.html",
    "475358e1-b0d3-4bb8-93c7-2fc9a142ef8a": MJ_HOST + "/comparison.md",
    "88d41417-0c1e-49e7-b415-eb9b7c9f931d": MJ_HOST + "/README.md",
    "39591a8f-2f44-4814-a4c9-63f2d2dca348": MJ_HOST + "/proof-of-execution.md",
    "5d7388ca-a5b1-4e48-b4eb-0cd25891472d": MJ_HOST + "/escrow-explainer.md",
    "565f1174-0cfe-44a9-a1bb-0ce1f6a64527": MJ_HOST + "/integration-guide.md",
    "d9e7dbf1-403d-49db-939d-a1d2a880ca66": MJ_HOST + "/first-person-paid-job.md",
}


def api(method: str, path: str, payload=None):
    h = {
        "Authorization": "Bearer " + env["MOLTJOBS_API_KEY"],
        "User-Agent": "MakeMoney-agent",
        "Accept": "application/json",
    }
    body = None
    if payload is not None:
        body = json.dumps(payload).encode()
        h["Content-Type"] = "application/json"
    req = request.Request(
        "https://api.moltjobs.io/v1" + path, data=body, headers=h, method=method
    )
    try:
        with request.urlopen(req, timeout=20) as r:
            return r.status, json.loads(r.read())
    except error.HTTPError as e:
        raw = e.read()
        try:
            return e.code, json.loads(raw)
        except Exception:
            return e.code, raw.decode("utf-8", "replace")[:300]


def deliver(job_id: str, status: str):
    url = MJ_URL.get(job_id)
    if not url:
        print("webhook skip unknown job", job_id[:8], flush=True)
        return
    if status in ("ASSIGNED", "assigned", "job.assigned"):
        s1, _ = api("PATCH", f"/jobs/{job_id}/start", {})
        print("webhook-start", job_id[:8], s1, flush=True)
    s2, _ = api(
        "PATCH",
        f"/jobs/{job_id}/submit",
        {"outputData": {"url": url, "kind": "public_url"}},
    )
    print("webhook-submit", job_id[:8], s2, flush=True)


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

    def log_message(self, fmt, *args):
        print("http", fmt % args, flush=True)

    def do_POST(self):
        if self.path.split("?")[0] not in ("/webhook", "/v1/webhook"):
            self.send_error(404)
            return
        n = int(self.headers.get("Content-Length") or 0)
        raw = self.rfile.read(n) if n else b"{}"
        try:
            body = json.loads(raw.decode("utf-8") or "{}")
        except Exception:
            body = {"raw": raw.decode("utf-8", "replace")[:400]}
        (HERE / "webhook.log").open("a").write(json.dumps(body)[:4000] + "\n")
        event = body.get("eventType") or body.get("type") or body.get("event") or ""
        data = body.get("data") or body.get("payload") or body
        job_id = (
            (data.get("jobId") if isinstance(data, dict) else None)
            or body.get("jobId")
            or (data.get("id") if isinstance(data, dict) else None)
        )
        status = (data.get("status") if isinstance(data, dict) else None) or event
        print("webhook", event, status, str(job_id)[:8] if job_id else None, flush=True)
        if job_id and (
            "assign" in str(event).lower()
            or str(status).upper() in ("ASSIGNED", "IN_PROGRESS")
        ):
            try:
                deliver(str(job_id), str(status))
            except Exception as e:
                print("webhook-deliver-err", type(e).__name__, flush=True)
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(b'{"ok":true}')


if __name__ == "__main__":
    httpd = ThreadingHTTPServer(("0.0.0.0", 8088), Handler)
    print("serve", HERE, "webhook", MJ_HOST + "/webhook", flush=True)
    httpd.serve_forever()
