#!/usr/bin/env python
"""Submit a signed MCSJ support escalation to Michel's Hermes webhook."""
from __future__ import annotations

import argparse
import hashlib
import hmac
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path

DEFAULT_LOCAL_URL = "http://127.0.0.1:8644/webhooks/ask-michel"
DEFAULT_LOCAL_SECRET_FILE = Path("C:/MCSJAgent/ask-michel-route-secret.txt")


def load_secret(path: str | None) -> str:
    secret = os.environ.get("MICHEL_WEBHOOK_SECRET", "").strip()
    if secret:
        return secret
    candidate = Path(path) if path else DEFAULT_LOCAL_SECRET_FILE
    if candidate.exists():
        return candidate.read_text(encoding="ascii").strip()
    raise SystemExit(
        "Missing signing secret. Set MICHEL_WEBHOOK_SECRET or pass --secret-file."
    )


def main() -> int:
    parser = argparse.ArgumentParser(description="Ask Michel for MCSJ backline help")
    parser.add_argument("question", help="The MCSJ question Foster needs researched")
    parser.add_argument("--context", default="", help="Customer/version/background context")
    parser.add_argument("--candidates", default="", help="Disputed answer/path candidates")
    parser.add_argument("--screenshot", action="store_true", help="Request an authentic screenshot")
    parser.add_argument("--request-id", default="", help="Optional caller-supplied idempotency ID")
    parser.add_argument("--origin-platform", default="")
    parser.add_argument("--origin-chat-id", default="")
    parser.add_argument("--origin-thread-id", default="")
    parser.add_argument("--origin-user-id", default="")
    parser.add_argument("--origin-user-name", default="")
    parser.add_argument("--origin-message-id", default="")
    parser.add_argument("--url", default=os.environ.get("MICHEL_WEBHOOK_URL", DEFAULT_LOCAL_URL))
    parser.add_argument("--secret-file", default=None)
    parser.add_argument("--timeout", type=int, default=30)
    args = parser.parse_args()

    request_id = args.request_id or f"foster-{int(time.time())}-{uuid.uuid4().hex[:8]}"
    payload = {
        "event_type": "ask_michel",
        "request_id": request_id,
        "question": args.question,
        "context": args.context,
        "candidates": args.candidates,
        "need_screenshot": "yes" if args.screenshot else "no",
        "requested_by": "foster",
        "origin": {
            "platform": args.origin_platform,
            "chat_id": args.origin_chat_id,
            "thread_id": args.origin_thread_id,
            "user_id": args.origin_user_id,
            "user_name": args.origin_user_name,
            "message_id": args.origin_message_id,
        },
    }
    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    signature = hmac.new(load_secret(args.secret_file).encode("utf-8"), body, hashlib.sha256).hexdigest()
    request = urllib.request.Request(
        args.url,
        data=body,
        method="POST",
        headers={
            "Content-Type": "application/json",
            "X-Webhook-Signature": signature,
            "X-Request-ID": request_id,
            "User-Agent": "Foster-Ask-Michel/1.0",
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=args.timeout) as response:
            text = response.read().decode("utf-8", errors="replace")
            print(json.dumps({"ok": True, "request_id": request_id, "status": response.status, "response": text}))
            return 0
    except urllib.error.HTTPError as exc:
        text = exc.read().decode("utf-8", errors="replace")
        print(json.dumps({"ok": False, "request_id": request_id, "status": exc.code, "response": text}), file=sys.stderr)
        return 1
    except Exception as exc:
        print(json.dumps({"ok": False, "request_id": request_id, "error": str(exc)}), file=sys.stderr)
        return 1


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