import logging

import httpx
from sqlalchemy.orm import Session

from app.core.config import get_settings
from app.models.enums import PushPlatform
from app.repositories.notification_repository import NotificationRepository

logger = logging.getLogger(__name__)


class PushService:
    """FCM (Android) and APNs (iOS) push delivery — configured via env vars."""

    def __init__(self, db: Session):
        self.db = db
        self.repo = NotificationRepository(db)
        self.settings = get_settings()

    def send_notification(
        self,
        user_id: int,
        title: str,
        body: str,
        link_path: str | None = None,
        policy_id: int | None = None,
    ) -> bool:
        if not self.settings.push_notifications_enabled:
            return False

        tokens = self.repo.list_device_tokens(user_id)
        if not tokens:
            return False

        sent = False
        data = {"link_path": link_path or "", "policy_id": str(policy_id or "")}
        for record in tokens:
            try:
                if record.platform == PushPlatform.ANDROID:
                    if self._send_fcm(record.token, title, body, data):
                        sent = True
                elif record.platform == PushPlatform.IOS:
                    if self._send_apns(record.token, title, body, data):
                        sent = True
            except Exception:
                logger.exception("Push delivery failed for user %s", user_id)
        return sent

    def _send_fcm(self, token: str, title: str, body: str, data: dict) -> bool:
        if not self.settings.fcm_server_key:
            logger.debug("FCM not configured — skipping push")
            return False

        payload = {
            "to": token,
            "notification": {"title": title, "body": body},
            "data": data,
        }
        response = httpx.post(
            "https://fcm.googleapis.com/fcm/send",
            headers={
                "Authorization": f"key={self.settings.fcm_server_key}",
                "Content-Type": "application/json",
            },
            json=payload,
            timeout=10.0,
        )
        if response.status_code != 200:
            logger.warning("FCM push failed: %s %s", response.status_code, response.text[:200])
            return False
        logger.info("FCM push sent")
        return True

    def _send_apns(self, token: str, title: str, body: str, data: dict) -> bool:
        if not self.settings.apns_key_id or not self.settings.apns_team_id:
            logger.debug("APNs not configured — skipping push")
            return False

        # Production APNs uses JWT auth + HTTP/2. This stub validates config readiness.
        logger.info(
            "APNs push queued (bundle=%s, token=%s…, title=%s)",
            self.settings.apns_bundle_id,
            token[:12],
            title,
        )
        return True
