"""GitHub integration for critical security alert issues."""

from __future__ import annotations

from typing import Any

from orchesis.integrations.base import AlertEvent, BaseIntegration
from orchesis.structured_log import StructuredLogger


def _get_httpx():
    try:
        import httpx

        return httpx
    except ImportError:
        raise ImportError(
            "httpx is required for GitHub integration. "
            "Install with: pip install orchesis[integrations]"
        ) from None


class GitHubIntegration(BaseIntegration):
    """GitHub issue and event integration."""

    def __init__(self, config: dict[str, Any] | str, repo: str | None = None):
        if isinstance(config, dict):
            super().__init__(config)
            token = str(config.get("token", "") or "")
            target_repo = str(config.get("repo", "") or "")
        else:
            token = str(config or "")
            target_repo = str(repo or "")
            super().__init__({"token": token, "repo": target_repo, "enabled": True})
        self._token = token
        self._repo = target_repo
        self._base = "https://api.github.com/repos"
        self._logger = StructuredLogger("github_integration")

    def _api_post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
        if not self._token or not self._repo:
            raise ValueError("GitHub token/repo not configured")
        httpx = _get_httpx()
        url = f"{self._base}/{self._repo}{path}"
        headers = {
            "Accept": "application/vnd.github+json",
            "Authorization": f"Bearer {self._token}",
            "X-GitHub-Api-Version": "2022-11-28",
        }
        response = httpx.post(url, headers=headers, json=payload, timeout=10.0)
        response.raise_for_status()
        data = response.json()
        return data if isinstance(data, dict) else {}

    def create_security_issue(self, event: AlertEvent) -> dict[str, Any]:
        """Create GitHub issue for critical security event."""
        body = f"""## 🚨 Security Alert from Orchesis

**Severity:** {event.severity.upper()}
**Rule:** {event.rule_id}
**Agent:** {event.agent_id}
**Time:** {event.timestamp}

### Details
{event.description}

### Pattern detected
{event.pattern}

### Recommended action
{event.remediation}

---
*Auto-generated by [Orchesis](https://orchesis.io) AI Agent Control Plane*
"""
        return self._api_post(
            "/issues",
            {
                "title": f"[Orchesis] {event.severity.upper()}: {event.rule_id} detected",
                "body": body,
                "labels": ["security", "ai-agent", f"severity:{event.severity}"],
            },
        )

    def send_webhook_event(self, event: AlertEvent) -> dict[str, Any]:
        """Send event to repository dispatch for GitHub Actions automation."""
        return self._api_post(
            "/dispatches",
            {
                "event_type": "orchesis_alert",
                "client_payload": {
                    "action": event.action,
                    "severity": event.severity,
                    "agent_id": event.agent_id,
                    "rule_id": event.rule_id,
                    "pattern": event.pattern,
                    "description": event.description,
                    "remediation": event.remediation,
                    "timestamp": event.timestamp,
                    "metadata": event.metadata if isinstance(event.metadata, dict) else {},
                },
            },
        )

    def send(self, event: AlertEvent) -> bool:
        try:
            create_issue_on = self.config.get("create_issue_on", [])
            issue_levels = {str(item).strip().lower() for item in create_issue_on} if isinstance(create_issue_on, list) else set()
            event_level = str(event.severity).strip().lower()
            if event_level in issue_levels:
                self.create_security_issue(event)
            else:
                self.send_webhook_event(event)
            return True
        except Exception as error:  # noqa: BLE001
            self._logger.warn("github integration failed", error=str(error))
            return False

