from __future__ import annotations

from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional, Union

from .encoding import encode_base64url
from .sign import public_key_from_secret


@dataclass
class DiscoveryOptions:
    agentId: str
    secretKey: Union[bytes, bytearray, str]
    agentName: Optional[str] = None
    agentVersion: Optional[str] = None
    receiptHeader: Optional[str] = None


def build_well_known_config(options: Union[DiscoveryOptions, Dict[str, Any]]) -> Dict[str, Any]:
    opts = options.__dict__ if isinstance(options, DiscoveryOptions) else dict(options)
    pk = public_key_from_secret(opts["secretKey"])

    return {
        "specVersion": "1.0",
        "canonicalization": "JCS-SORTED-UTF8-NOWS",
        "signatureAlgorithms": ["Ed25519"],
        "hashAlgorithms": ["sha256"],
        "receiptHeader": opts.get("receiptHeader") or "X-AAR-Receipt",
        "agent": {
            "id": opts["agentId"],
            "name": opts.get("agentName"),
            "version": opts.get("agentVersion"),
            "publicKey": encode_base64url(pk),
        },
    }


def well_known_handler(options: Union[DiscoveryOptions, Dict[str, Any]]) -> Callable[[Any, Any], None]:
    config = build_well_known_config(options)

    def _handler(_req: Any, res: Any) -> None:
        res.json(config)

    return _handler


buildWellKnownConfig = build_well_known_config
wellKnownHandler = well_known_handler

__all__ = [
    "DiscoveryOptions",
    "build_well_known_config",
    "buildWellKnownConfig",
    "well_known_handler",
    "wellKnownHandler",
]
