"""Native Foster tool for correlated, source-routed Michel verification."""
from __future__ import annotations

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

from gateway.session_context import get_session_env
from tools.registry import registry

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


def _available() -> bool:
    return _SECRET_FILE.is_file()


def ask_michel_verify(
    question: str,
    proposed_answer: str = "",
    context: str = "",
    need_screenshot: bool = False,
    task_id: str | None = None,
) -> str:
    platform = get_session_env("HERMES_SESSION_PLATFORM", "")
    chat_id = get_session_env("HERMES_SESSION_CHAT_ID", "")
    if not platform or not chat_id:
        return json.dumps({
            "ok": False,
            "error": "No active gateway origin; ask_michel_verify requires a user chat session.",
        })
    if platform != "telegram":
        return json.dumps({
            "ok": False,
            "error": f"Origin platform {platform!r} is not enabled for correlated return delivery yet.",
        })

    request_id = f"foster-{int(time.time())}-{uuid.uuid4().hex[:8]}"
    payload = {
        "event_type": "ask_michel",
        "request_id": request_id,
        "question": question,
        "context": context,
        "candidates": proposed_answer,
        "need_screenshot": "yes" if need_screenshot else "no",
        "requested_by": "foster",
        "origin": {
            "platform": platform,
            "chat_id": chat_id,
            "chat_name": get_session_env("HERMES_SESSION_CHAT_NAME", ""),
            "thread_id": get_session_env("HERMES_SESSION_THREAD_ID", ""),
            "user_id": get_session_env("HERMES_SESSION_USER_ID", ""),
            "user_name": get_session_env("HERMES_SESSION_USER_NAME", ""),
            "message_id": get_session_env("HERMES_SESSION_MESSAGE_ID", ""),
        },
    }
    body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    secret = _SECRET_FILE.read_text(encoding="ascii").strip()
    signature = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
    request = urllib.request.Request(
        os.environ.get("MICHEL_WEBHOOK_URL", _DEFAULT_URL),
        data=body,
        method="POST",
        headers={
            "Content-Type": "application/json",
            "X-Webhook-Signature": signature,
            "X-Request-ID": request_id,
            "User-Agent": "Foster-Ask-Michel-Tool/2.0",
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            response.read()
            if response.status != 202:
                return json.dumps({
                    "ok": False,
                    "request_id": request_id,
                    "status": response.status,
                })
            return json.dumps({
                "ok": True,
                "request_id": request_id,
                "status": 202,
                "delivery": "Michel will verify asynchronously and Foster will return the result to this originating conversation.",
            })
    except urllib.error.HTTPError as exc:
        exc.read()
        return json.dumps({
            "ok": False,
            "request_id": request_id,
            "status": exc.code,
            "error": "Michel verification request rejected.",
        })
    except Exception as exc:
        return json.dumps({
            "ok": False,
            "request_id": request_id,
            "error": str(exc),
        })


ASK_MICHEL_SCHEMA = {
    "name": "ask_michel_verify",
    "description": (
        "Delegate an MCSJ answer to Michel for independent source/demo verification. "
        "Use when the user asks Foster to verify, check, confirm, or arbitrate an MCSJ answer with Michel. "
        "The completed result is routed automatically back to the current originating Telegram conversation."
    ),
    "parameters": {
        "type": "object",
        "properties": {
            "question": {"type": "string", "description": "The user's original MCSJ question."},
            "proposed_answer": {"type": "string", "description": "Foster's answer or disputed candidate to verify."},
            "context": {"type": "string", "description": "Customer, version, and relevant background."},
            "need_screenshot": {"type": "boolean", "description": "Whether Michel should provide authentic screenshot proof."},
        },
        "required": ["question", "proposed_answer"],
    },
}


registry.register(
    name="ask_michel_verify",
    toolset="mcsj",
    schema=ASK_MICHEL_SCHEMA,
    handler=lambda args, **kw: ask_michel_verify(
        question=args.get("question", ""),
        proposed_answer=args.get("proposed_answer", ""),
        context=args.get("context", ""),
        need_screenshot=bool(args.get("need_screenshot", False)),
        task_id=kw.get("task_id"),
    ),
    check_fn=_available,
    emoji="🔎",
)
