"""did:web identity adapter (§2.3 core). Resolves a `did:web:...` identifier to a verification key, then
delegates to the matching signature verifier (Ed25519 / ES256). Resolution is INJECTED (a `DidResolver`
callback) so the harness never makes a network call; a production deployment's resolver fetches
`https://<domain>/.well-known/did.json` and extracts the verification method. The adapter itself is real —
only key discovery is pluggable.
"""

from __future__ import annotations

from typing import Callable, Optional, Tuple

from cl.identity.signatures import Ed25519Verifier, Es256Verifier
from cl.interfaces.identity import AssuranceLevel, IdentityVerifier, VerifiedIdentity

# A resolver maps a did:web identifier → (algorithm, public_key_hex), or None if unresolvable.
DidResolver = Callable[[str], Optional[Tuple[str, str]]]


class DidWebVerifier(IdentityVerifier):
    def __init__(self, resolver: DidResolver):
        self._resolve = resolver
        self._delegates = {"ed25519": Ed25519Verifier(), "es256": Es256Verifier()}

    def method(self) -> str:
        return "did:web"

    def verify(self, signing_input: bytes, signature: bytes, key_ref: str) -> Optional[VerifiedIdentity]:
        # key_ref is the did:web identifier (e.g. "did:web:example.com:agents:7")
        if not key_ref.startswith("did:web:"):
            return None
        resolved = self._resolve(key_ref)
        if resolved is None:
            return None
        algorithm, public_key_hex = resolved
        delegate = self._delegates.get(algorithm)
        if delegate is None:
            return None
        inner = delegate.verify(signing_input, signature, public_key_hex)
        if inner is None:
            return None
        # the proof is real; the SUBJECT is the DID (not the bare key)
        return VerifiedIdentity(subject_ref=key_ref, method="did:web", assurance=AssuranceLevel.SIGNED)
