#!/usr/bin/env python3
from __future__ import annotations

import mimetypes
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple

if TYPE_CHECKING:
    from cheapclaw_service import CheapClawService


class ChannelAdapter:
    name = "base"

    def __init__(
        self,
        config: Dict[str, Any],
        service: "CheapClawService",
        *,
        logger: Optional[Callable[[str], None]] = None,
    ):
        self.config = config
        self.service = service
        self._logger = logger

    def log(self, message: str) -> None:
        if self._logger is not None:
            self._logger(str(message))

    def poll_events(self) -> List[Dict[str, Any]]:
        return []

    def send_message(
        self,
        conversation_id: str,
        message: str,
        attachments: Optional[List[Dict[str, Any]]] = None,
    ) -> Tuple[bool, str]:
        raise NotImplementedError

    @staticmethod
    def _normalize_attachments(attachments: Optional[List[Dict[str, Any]]]) -> List[Dict[str, Any]]:
        items = []
        for item in attachments or []:
            if not isinstance(item, dict):
                continue
            local_path = str(item.get("local_path") or item.get("path") or "").strip()
            if not local_path:
                continue
            path = Path(local_path).expanduser().resolve()
            if not path.exists() or not path.is_file():
                continue
            guessed_mime = mimetypes.guess_type(str(path))[0] or "application/octet-stream"
            items.append(
                {
                    "path": path,
                    "filename": str(item.get("filename") or path.name),
                    "mime_type": str(item.get("mime_type") or guessed_mime),
                    "kind": str(item.get("kind") or "auto").strip().lower() or "auto",
                    "caption": str(item.get("caption") or "").strip(),
                }
            )
        return items

    def handle_webhook_get(
        self,
        path: str,
        query: Dict[str, List[str]],
        headers: Dict[str, str],
    ) -> Tuple[int, Dict[str, str], bytes]:
        return 404, {"Content-Type": "text/plain; charset=utf-8"}, b"not found"

    def handle_webhook_post(
        self,
        path: str,
        body: bytes,
        headers: Dict[str, str],
    ) -> Tuple[int, Dict[str, str], bytes]:
        return 404, {"Content-Type": "text/plain; charset=utf-8"}, b"not found"
