"""
Service Registry – Verzeichnis aller AI-Agent Services.
Agenten registrieren sich hier mit Wallet, Service-Typ und Preis.

In Produktion: Könnte on-chain sein oder als gehosteter Service laufen.
"""
from __future__ import annotations
import json
import os
import time
from dataclasses import dataclass, asdict


@dataclass
class ServiceListing:
    """Ein Service-Eintrag in der Registry."""
    wallet: str
    service_type: str
    price_usd: float
    description: str = ""
    endpoint: str = ""          # API-Endpoint des Services
    registered_at: str = ""
    active: bool = True


class ServiceRegistry:
    """
    Service-Verzeichnis für AI-Agent Services.
    Agenten registrieren ihre Services hier,
    andere Agenten finden und buchen sie.
    """

    def __init__(self, storage_path: str = ""):
        if not storage_path:
            storage_path = os.path.join(os.path.dirname(__file__), "..", "registry.json")
        self.storage_path = os.path.abspath(storage_path)
        self._registry: dict[str, dict] = self._load()

    def _load(self) -> dict:
        if os.path.exists(self.storage_path):
            with open(self.storage_path, "r") as f:
                return json.load(f)
        return {}

    def _save(self):
        with open(self.storage_path, "w") as f:
            json.dump(self._registry, f, indent=2, ensure_ascii=False)

    def register(self, listing: ServiceListing) -> str:
        """
        Registriert einen Service in der Registry.

        Returns:
            Service-ID
        """
        if not listing.registered_at:
            listing.registered_at = time.strftime("%Y-%m-%dT%H:%M:%SZ")

        service_id = f"{listing.service_type}:{listing.wallet[:8]}"
        self._registry[service_id] = asdict(listing)
        self._save()
        return service_id

    def find(self, service_type: str) -> list[dict]:
        """Findet alle aktiven Anbieter für einen Service-Typ."""
        results = []
        for sid, info in self._registry.items():
            if (info.get("service_type", "").lower() == service_type.lower()
                    and info.get("active", True)):
                results.append({"id": sid, **info})
        return results

    def find_cheapest(self, service_type: str) -> dict | None:
        """Findet den günstigsten Anbieter für einen Service-Typ."""
        providers = self.find(service_type)
        if not providers:
            return None
        return min(providers, key=lambda p: p["price_usd"])

    def list_all(self) -> list[dict]:
        """Gibt alle registrierten Services zurück."""
        return [{"id": sid, **info} for sid, info in self._registry.items()]

    def deregister(self, service_id: str):
        """Deaktiviert einen Service."""
        if service_id in self._registry:
            self._registry[service_id]["active"] = False
            self._save()
