"""Connector to the client service: language and user lists (docs/dev/aga/service-connector.md).

Snapfile calls ``GET {service_base_url}/snapfile/{languages,users}`` signed with the shared secret and keeps the
last good answer on the project for 10 minutes; if the service is down the last answer is returned as stale.
Without a configured connector the lists are empty: nothing is ever invented.
"""

from __future__ import annotations

import json
import logging
import time
from datetime import datetime, timedelta
from typing import Any
from urllib.parse import urlsplit

from django.utils import timezone

from snapfile.core import http
from snapfile.core.crypto import decrypt_secret
from snapfile.jobs.webhooks import signature
from snapfile.projects.models import Project

log = logging.getLogger("snapfile.integration")
CACHE_TTL = timedelta(minutes=10)
KINDS = ("languages", "users")


def _clean(kind: str, payload: Any) -> list[dict[str, Any]]:
    raw = payload.get("items") if isinstance(payload, dict) else payload
    if not isinstance(raw, list):
        raise ValueError("items must be a list")
    out: list[dict[str, Any]] = []
    for item in raw:
        if not isinstance(item, dict):
            continue
        if kind == "languages" and item.get("code"):
            out.append({"code": str(item["code"]), "name": str(item.get("name") or item["code"])})
        elif kind == "users" and item.get("id") is not None:
            out.append(
                {
                    "id": str(item["id"]),
                    "name": str(item.get("name") or ""),
                    "email": str(item["email"]) if item.get("email") else None,
                }
            )
    return out


def _fetch(project: Project, kind: str) -> list[dict[str, Any]]:
    url = f"{(project.service_base_url or '').rstrip('/')}/snapfile/{kind}"
    ts = int(time.time())
    message = f"GET {urlsplit(url).path}".encode()
    secret = decrypt_secret(project.service_secret_enc) if project.service_secret_enc else ""
    resp = http.request(
        "GET",
        url,
        headers={
            "Accept": "application/json",
            "X-Snapfile-Project": project.slug,
            "X-Snapfile-Timestamp": str(ts),
            "X-Snapfile-Signature": signature(secret or "", ts, message),
        },
        timeout=5.0,
        max_bytes=2 * 1024 * 1024,
    )
    if not 200 <= resp.status < 300:
        raise ValueError(f"HTTP {resp.status}")
    return _clean(kind, json.loads(resp.data))


def probe(project: Project) -> dict[str, Any]:
    """Ask the service for both lists right now, past the cache; the answer says what is wrong with each."""
    out: dict[str, Any] = {}
    for kind in ("languages", "users"):
        try:
            out[kind] = {"ok": True, "count": len(_fetch(project, kind))}
        except (http.FetchError, ValueError, OSError) as exc:
            out[kind] = {"ok": False, "error": str(exc)[:200]}
    project.service_cache = {}
    Project.objects.filter(pk=project.pk).update(service_cache={})
    return out


def service_list(project: Project, kind: str) -> dict[str, Any]:
    if not project.service_base_url:
        return {"configured": False, "stale": False, "items": []}
    cache = (project.service_cache or {}).get(kind) or {}
    fetched_at = cache.get("at")
    if fetched_at and timezone.now() - datetime.fromisoformat(fetched_at) < CACHE_TTL:
        return {"configured": True, "stale": False, "items": cache.get("items") or []}
    try:
        items = _fetch(project, kind)
    except (http.FetchError, ValueError, OSError) as exc:
        log.warning("service connector failed", extra={"project": project.slug, "kind": kind, "error": str(exc)})
        return {"configured": True, "stale": True, "items": cache.get("items") or []}
    entry = {"at": timezone.now().isoformat(), "items": items}
    project.service_cache = {**(project.service_cache or {}), kind: entry}
    Project.objects.filter(pk=project.pk).update(service_cache=project.service_cache)
    return {"configured": True, "stale": False, "items": items}
