#!/usr/bin/env python3
"""Submit a signed Foster-to-Michel request through the local SSH tunnel."""
from __future__ import annotations
import argparse, hashlib, hmac, json, os, sys, time, urllib.error, urllib.request, uuid
from pathlib import Path

DEFAULT_URL = "http://127.0.0.1:18644/webhooks/ask-michel"
DEFAULT_SECRET = Path.home() / ".config/foster-ask-michel/secret"

def load_secret(path: str | None) -> str:
    secret = os.environ.get("MICHEL_WEBHOOK_SECRET", "").strip()
    if secret:
        return secret
    candidate = Path(path).expanduser() if path else DEFAULT_SECRET
    if candidate.exists():
        return candidate.read_text(encoding="ascii").strip()
    raise SystemExit(f"Missing signing secret: {candidate}")

def main() -> int:
    p = argparse.ArgumentParser(description="Ask Michel for MCSJ backline help")
    p.add_argument("question")
    p.add_argument("--context", default="")
    p.add_argument("--candidates", default="")
    p.add_argument("--screenshot", action="store_true")
    p.add_argument("--request-id", default="")
    p.add_argument("--origin-platform", default="")
    p.add_argument("--origin-chat-id", default="")
    p.add_argument("--origin-thread-id", default="")
    p.add_argument("--origin-user-id", default="")
    p.add_argument("--origin-user-name", default="")
    p.add_argument("--origin-message-id", default="")
    p.add_argument("--url", default=os.environ.get("MICHEL_WEBHOOK_URL", DEFAULT_URL))
    p.add_argument("--secret-file", default=None)
    p.add_argument("--timeout", type=int, default=30)
    a = p.parse_args()
    request_id = a.request_id or f"foster-{int(time.time())}-{uuid.uuid4().hex[:8]}"
    payload = {"event_type":"ask_michel","request_id":request_id,"question":a.question,
               "context":a.context,"candidates":a.candidates,
               "need_screenshot":"yes" if a.screenshot else "no","requested_by":"foster"}
    payload["origin"] = {
        "platform": a.origin_platform, "chat_id": a.origin_chat_id,
        "thread_id": a.origin_thread_id, "user_id": a.origin_user_id,
        "user_name": a.origin_user_name, "message_id": a.origin_message_id,
    }
    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
    sig = hmac.new(load_secret(a.secret_file).encode(), body, hashlib.sha256).hexdigest()
    req = urllib.request.Request(a.url, data=body, method="POST", headers={
        "Content-Type":"application/json","X-Webhook-Signature":sig,
        "X-Request-ID":request_id,"User-Agent":"Foster-Ask-Michel/1.0"})
    try:
        with urllib.request.urlopen(req, timeout=a.timeout) as r:
            print(json.dumps({"ok":True,"request_id":request_id,"status":r.status,
                              "response":r.read().decode(errors="replace")}))
            return 0
    except urllib.error.HTTPError as e:
        print(json.dumps({"ok":False,"request_id":request_id,"status":e.code,
                          "response":e.read().decode(errors="replace")}), file=sys.stderr)
    except Exception as e:
        print(json.dumps({"ok":False,"request_id":request_id,"error":str(e)}), file=sys.stderr)
    return 1

if __name__ == "__main__":
    raise SystemExit(main())
