"""Meeting transcript -> action items, as a webhook.

POST /webhook with JSON {"transcript": "...", "meeting": "Weekly sync"} and the header
X-Webhook-Secret. Returns {"summary": "...", "items": [{"task", "owner", "due"}]} and, if
FORWARD_URL is set, posts a plain-text digest there (Slack-style {"text": ...}) and adds
"forwarded": true or false to the reply.

    python3 -m venv .venv && . .venv/bin/activate
    pip install anthropic pydantic
    export ANTHROPIC_API_KEY=...  WEBHOOK_SECRET=...  [FORWARD_URL=...]  [HOST=127.0.0.1]  [PORT=8080]
    python meeting_actions.py

The input is a transcript, not audio: export it from your meeting tool or transcribe first.
"""

import hmac
import json
import os
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from pydantic import BaseModel

MODEL = os.getenv("MODEL", "claude-sonnet-5-5")
MAX_BODY = 1_000_000  # bytes; a one-hour transcript is well under this

SYSTEM = """You turn a meeting transcript into action items.
List only tasks that someone in the meeting agreed to or was asked to do. For each: the task in
one imperative sentence, the owner as named in the transcript, and the due date as stated.
If the owner or the date was not said, write "unassigned" or "no date". Do not guess.
If there are no action items, return an empty list. The summary is two sentences at most."""


class Item(BaseModel):
    task: str
    owner: str
    due: str


class ActionItems(BaseModel):
    summary: str
    items: list[Item]


def extract(transcript: str, meeting: str) -> ActionItems:
    import anthropic

    response = anthropic.Anthropic().messages.parse(
        model=MODEL,
        max_tokens=4000,
        system=SYSTEM,
        messages=[{"role": "user", "content": f"Meeting: {meeting}\n\nTranscript:\n{transcript}"}],
        output_format=ActionItems,
    )
    if response.parsed_output is None:
        raise RuntimeError(f"model returned no usable result (stop_reason={response.stop_reason})")
    return response.parsed_output


def digest(meeting: str, result: ActionItems) -> str:
    lines = [f"{meeting}: {result.summary}"]
    lines += [f"- {item.task} ({item.owner}, {item.due})" for item in result.items]
    return "\n".join(lines) if result.items else lines[0] + "\nNo action items."


def forward(url: str, text: str) -> None:
    request = urllib.request.Request(url, data=json.dumps({"text": text}).encode(),
                                     headers={"Content-Type": "application/json"})
    urllib.request.urlopen(request, timeout=15).close()


class Handler(BaseHTTPRequestHandler):
    timeout = 30  # seconds per socket read: a stalled client cannot hold a thread forever
    extract = staticmethod(extract)  # replaced in tests
    forward = staticmethod(forward)

    def reply(self, status: int, body: dict) -> None:
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_POST(self) -> None:
        if self.path != "/webhook":
            return self.reply(404, {"error": "not found"})
        secret = os.getenv("WEBHOOK_SECRET", "")
        given = self.headers.get("X-Webhook-Secret", "")
        if not secret or not hmac.compare_digest(given.encode(), secret.encode()):
            return self.reply(401, {"error": "bad or missing X-Webhook-Secret"})
        try:
            length = int(self.headers.get("Content-Length", ""))
        except ValueError:
            return self.reply(411, {"error": "Content-Length required"})
        if length < 0:
            return self.reply(400, {"error": "bad Content-Length"})
        if length > MAX_BODY:
            return self.reply(413, {"error": "transcript too large"})
        try:
            payload = json.loads(self.rfile.read(length))
            transcript = payload["transcript"].strip()
            meeting = str(payload.get("meeting") or "Meeting")
        except (ValueError, KeyError, TypeError, AttributeError, RecursionError):
            return self.reply(400, {"error": 'send JSON like {"transcript": "...", "meeting": "..."}'})
        if not transcript:
            return self.reply(400, {"error": "transcript is empty"})

        try:
            result = self.extract(transcript, meeting)
        except Exception as error:  # details stay in the server log: they can quote the transcript
            print(f"model call failed: {type(error).__name__}", flush=True)
            return self.reply(502, {"error": "model call failed, see the server log"})

        body = result.model_dump()
        url = os.getenv("FORWARD_URL")
        if url:
            try:
                self.forward(url, digest(meeting, result))
                body["forwarded"] = True
            except Exception as error:  # the caller still gets the items; the URL is a secret
                print(f"forward failed: {type(error).__name__}", flush=True)
                body["forwarded"] = False
        self.reply(200, body)

    def log_message(self, fmt, *args) -> None:  # no transcripts or secrets in logs
        line = f"{getattr(self, 'command', '-')} {getattr(self, 'path', '-')}"
        print(f"{line} -> {args[1] if len(args) > 1 else ''}", flush=True)


if __name__ == "__main__":
    # Local only by default. To expose it, set HOST=0.0.0.0 and put it behind HTTPS:
    # over plain HTTP the secret and the transcript travel unencrypted.
    host, port = os.getenv("HOST", "127.0.0.1"), int(os.getenv("PORT", "8080"))
    print(f"listening on http://{host}:{port}/webhook", flush=True)
    ThreadingHTTPServer((host, port), Handler).serve_forever()
