"""Gateway-backed Microsoft Copilot enrichment client for BLCE Excel Wizard."""
from __future__ import annotations

import json
import logging
from typing import Any, Dict, Optional
from urllib import error, request

logger = logging.getLogger(__name__)


class CopilotGatewayClient:
    """Call DataBridge gateway service that brokers Graph Copilot auth/tokens."""

    def __init__(self, gateway_url: str = "", timeout_seconds: int = 20):
        self.gateway_url = gateway_url.strip().rstrip("/")
        self.timeout_seconds = timeout_seconds

    def is_enabled(self) -> bool:
        return bool(self.gateway_url)

    def enrich_workbook_context(
        self,
        *,
        file_path: str,
        prompt_hint: str = "",
        workbook_context: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Request Copilot enrichment for a workbook context via gateway."""
        if not self.gateway_url:
            return {"status": "disabled", "reason": "gateway_url_not_configured"}

        payload = {
            "file_path": file_path,
            "prompt_hint": prompt_hint,
            "workbook_context": workbook_context or {},
        }
        body = json.dumps(payload).encode("utf-8")

        req = request.Request(
            url=f"{self.gateway_url}/copilot/excel/enrich",
            data=body,
            method="POST",
            headers={"Content-Type": "application/json"},
        )
        try:
            with request.urlopen(req, timeout=self.timeout_seconds) as resp:
                raw = resp.read().decode("utf-8")
                return json.loads(raw) if raw else {"status": "ok", "data": {}}
        except error.HTTPError as exc:
            return {
                "status": "error",
                "error": f"http_error:{exc.code}",
                "message": str(exc),
            }
        except Exception as exc:
            logger.debug("Copilot gateway call failed: %s", exc)
            return {
                "status": "error",
                "error": "gateway_unavailable",
                "message": str(exc),
            }

