"""Doubao Mini Program HTTP signing and response decryption.

Protocol-compatible with Ocean cloud-secret-sdk v1.6.11.  ``verify_sign``
performs local cryptographic verification.  Production servers should also
pass a ``nonce_verifier`` backed by Ocean VerifyNonce (or an equivalent shared
replay-prevention service).
"""

from __future__ import annotations

import base64
import hashlib
import os
import re
import struct
import time
from collections.abc import Callable
from typing import Optional
from urllib.parse import parse_qsl, unquote, urlsplit

from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, utils
from cryptography.hazmat.primitives.ciphers.aead import AESGCM


class DoubaoSecret:
    SIGN_ALGORITHM = "ECDSA_SHA256"
    VERSION = "1"
    AUTH_HEADER_NAME = "x-doubao-authorization"
    AUTH_HEADER_FORMAT = (
        'algorithm="{algorithm}",version="{version}",signature="{signature}",'
        'cert_serial="{cert_serial}",nonce="{nonce}",timestamp="{timestamp}"'
    )
    _AUTH_PART = re.compile(r'([A-Za-z0-9_]+)="([A-Za-z0-9+/=_-]*)"')
    _SERIAL = re.compile(r"[0-9a-f]+")
    _NONCE = re.compile(r"[A-Za-z0-9_-]{16}")
    _SUPPORTED_METHODS = {
        "GET", "HEAD", "POST", "PUT", "PATCH",
        "DELETE", "CONNECT", "OPTIONS", "TRACE",
    }

    # Ocean SDK generates 12 random bytes -> exactly 16 padded Base64URL chars.
    NONCE_BYTES = 12

    TLV_HEADER_BYTES = 6
    TLV_VERSION_VALUE_BYTES = 2
    SUPPORTED_TLV_VERSION_VALUE = 1
    TLV_VERSION = 0x0001
    TLV_EPHEMERAL_PUB_KEY = 0x0002
    TLV_DATA_KEY_CIPHER = 0x0003
    TLV_DATA_CIPHER = 0x0004

    EC_POINT_UNCOMPRESSED_BYTES = 65
    AES_GCM_IV_BYTES = 12
    AES_GCM_TAG_BYTES = 16
    EC_NAMED_CURVE = ec.SECP256R1()

    @staticmethod
    def sign(
        method: str,
        path: str,
        query: Optional[str],
        body: Optional[str],
        pem_ec_private_key: str,
        cert_serial: str,
        *,
        timestamp_seconds: Optional[int] = None,
        nonce: Optional[str] = None,
        debug_print_sign_content: bool = False,
    ) -> str:
        timestamp = int(time.time()) if timestamp_seconds is None else int(timestamp_seconds)
        nonce_value = nonce if nonce is not None else DoubaoSecret._generate_nonce()
        DoubaoSecret._validate_signing_nonce(nonce_value)
        cert_serial = (cert_serial or "").lower()
        DoubaoSecret._validate_cert_serial(cert_serial)

        private_key = DoubaoSecret._load_private_key(pem_ec_private_key)
        sign_content = DoubaoSecret._build_sign_content(
            method, path, query or "", body or "", timestamp, nonce_value
        )
        if debug_print_sign_content:
            print(sign_content)

        digest = hashlib.sha256(sign_content.encode("utf-8")).digest()
        signature_der = private_key.sign(
            digest, ec.ECDSA(utils.Prehashed(hashes.SHA256()))
        )
        signature = base64.urlsafe_b64encode(signature_der).decode("ascii")
        return DoubaoSecret.AUTH_HEADER_FORMAT.format(
            algorithm=DoubaoSecret.SIGN_ALGORITHM,
            version=DoubaoSecret.VERSION,
            signature=signature,
            cert_serial=cert_serial,
            nonce=nonce_value,
            timestamp=timestamp,
        )

    @staticmethod
    def verify_sign(
        method: str,
        path: str,
        query: Optional[str],
        body: Optional[str],
        authorization_header: str,
        pem_cert: str,
        *,
        nonce_verifier: Optional[Callable[[str, int], bool]] = None,
        debug_print_sign_content: bool = False,
    ) -> bool:
        """Verify the signature and optionally perform distributed replay checks.

        ``nonce_verifier`` should implement the same semantics as Ocean
        ``VerifyNonce(nonce, timestamp, appID)``.  Without it this method only
        proves integrity/authenticity; it does not prevent replay.
        """
        auth = DoubaoSecret._parse_authorization_header(authorization_header)
        timestamp = int(auth["timestamp"])
        if timestamp <= 0:
            raise ValueError("authorization timestamp must be positive")

        cert = DoubaoSecret._load_certificate(pem_cert)
        expected_serial = DoubaoSecret._certificate_serial(cert)
        if auth["cert_serial"].lower() != expected_serial:
            raise ValueError("authorization cert_serial does not match certificate")

        public_key = cert.public_key()
        if not isinstance(public_key, ec.EllipticCurvePublicKey):
            raise ValueError("EC public key required in certificate")
        signature = DoubaoSecret._b64url_decode_strict(auth["signature"])
        sign_content = DoubaoSecret._build_sign_content(
            method, path, query or "", body or "", timestamp, auth["nonce"]
        )
        if debug_print_sign_content:
            print(sign_content)

        digest = hashlib.sha256(sign_content.encode("utf-8")).digest()
        try:
            public_key.verify(
                signature, digest, ec.ECDSA(utils.Prehashed(hashes.SHA256()))
            )
        except InvalidSignature:
            return False
        if nonce_verifier is not None and not nonce_verifier(auth["nonce"], timestamp):
            return False
        return True

    @staticmethod
    def decrypt(cipher_data_b64url: str, pem_ec_private_key: str) -> str:
        if not cipher_data_b64url:
            raise ValueError("cipher_data_b64url is required")
        blob = DoubaoSecret._b64url_decode_lenient(cipher_data_b64url)
        fields: dict[int, bytes] = {}
        offset = 0
        while offset < len(blob):
            if len(blob) - offset < DoubaoSecret.TLV_HEADER_BYTES:
                raise ValueError("invalid TLV header")
            tag, length = struct.unpack_from(">HI", blob, offset)
            offset += DoubaoSecret.TLV_HEADER_BYTES
            if length > len(blob) - offset:
                raise ValueError("invalid TLV length")
            fields[tag] = blob[offset : offset + length]
            offset += length

        version_bytes = fields.get(DoubaoSecret.TLV_VERSION)
        if version_bytes is None or len(version_bytes) != 2:
            raise ValueError("missing or invalid TLV version")
        version = struct.unpack(">H", version_bytes)[0]
        if version != DoubaoSecret.SUPPORTED_TLV_VERSION_VALUE:
            raise ValueError(f"unsupported TLV version: {version}")

        ephemeral = fields.get(DoubaoSecret.TLV_EPHEMERAL_PUB_KEY)
        data_key_cipher = fields.get(DoubaoSecret.TLV_DATA_KEY_CIPHER)
        data_cipher = fields.get(DoubaoSecret.TLV_DATA_CIPHER)
        if not ephemeral or not data_key_cipher or not data_cipher:
            raise ValueError("missing required TLV fields")
        if len(ephemeral) != DoubaoSecret.EC_POINT_UNCOMPRESSED_BYTES or ephemeral[0] != 0x04:
            raise ValueError("invalid ephemeral public key")

        private_key = DoubaoSecret._load_private_key(pem_ec_private_key)
        ephemeral_key = ec.EllipticCurvePublicKey.from_encoded_point(
            DoubaoSecret.EC_NAMED_CURVE, ephemeral
        )
        shared_secret = private_key.exchange(ec.ECDH(), ephemeral_key)
        kek = hashlib.sha256(shared_secret).digest()
        data_key = DoubaoSecret._aes_gcm_decrypt(kek, data_key_cipher)
        plaintext = DoubaoSecret._aes_gcm_decrypt(data_key, data_cipher)
        return plaintext.decode("utf-8")

    @staticmethod
    def _build_canonical_query(query: str) -> str:
        if not query:
            return ""
        if ";" in query:
            raise ValueError("invalid query string: unescaped semicolon")
        DoubaoSecret._validate_percent_encoding(query)
        pairs = parse_qsl(
            query,
            keep_blank_values=True,
            strict_parsing=False,
            encoding="utf-8",
            errors="strict",
            separator="&",
        )
        # Ocean SDK sorts keys and then independently sorts values per key.
        pairs.sort(key=lambda item: (item[0], item[1]))
        return "&".join(f"{key}={value}" for key, value in pairs)

    @staticmethod
    def _build_sign_content(
        method: str, path: str, query: str, body: str, timestamp: int, nonce: str
    ) -> str:
        DoubaoSecret._validate_method_and_path(method, path)
        if timestamp <= 0:
            raise ValueError("timestamp must be positive")
        DoubaoSecret._validate_nonce(nonce)
        canonical_query = DoubaoSecret._build_canonical_query(query)
        body_hash = hashlib.sha256(body.encode("utf-8")).hexdigest()
        return f"{method}\n{path}\n{canonical_query}\n{body_hash}\n{timestamp}\n{nonce}"

    @staticmethod
    def _parse_authorization_header(header: str) -> dict[str, str]:
        if not header:
            raise ValueError("x-doubao-authorization is required")
        fields: dict[str, str] = {}
        for raw_part in header.split(","):
            match = DoubaoSecret._AUTH_PART.fullmatch(raw_part.strip())
            if match is None:
                raise ValueError("invalid x-doubao-authorization format")
            key, value = match.groups()
            if key in fields:
                raise ValueError(f"duplicate authorization field: {key}")
            fields[key] = value
        for key in ("algorithm", "version", "signature", "cert_serial", "nonce", "timestamp"):
            if not fields.get(key):
                raise ValueError(f"missing authorization field: {key}")
        if fields["algorithm"] != DoubaoSecret.SIGN_ALGORITHM or fields["version"] != DoubaoSecret.VERSION:
            raise ValueError("unsupported authorization algorithm or version")
        DoubaoSecret._validate_verification_cert_serial(fields["cert_serial"])
        DoubaoSecret._validate_nonce(fields["nonce"])
        if not fields["timestamp"].isdigit():
            raise ValueError("authorization timestamp must be an integer")
        return fields

    @staticmethod
    def _validate_method_and_path(method: str, path: str) -> None:
        if method not in DoubaoSecret._SUPPORTED_METHODS:
            raise ValueError(f"unsupported HTTP method {method!r}; method must be uppercase")
        parsed = urlsplit(path)
        if (
            not path.startswith("/")
            or parsed.scheme
            or parsed.netloc
            or parsed.query
            or parsed.fragment
            or unquote(path, encoding="utf-8", errors="strict") != path
        ):
            raise ValueError(f"invalid request path: {path!r}")

    @staticmethod
    def _validate_percent_encoding(value: str) -> None:
        for index, char in enumerate(value):
            if char == "%" and (
                index + 2 >= len(value)
                or not all(c in "0123456789abcdefABCDEF" for c in value[index + 1 : index + 3])
            ):
                raise ValueError("invalid percent escape in query string")

    @staticmethod
    def _validate_nonce(nonce: str) -> None:
        if re.fullmatch(r"[A-Za-z0-9_-]+", nonce or "") is None:
            raise ValueError("nonce must be non-empty Base64URL text")

    @staticmethod
    def _validate_signing_nonce(nonce: str) -> None:
        if DoubaoSecret._NONCE.fullmatch(nonce or "") is None:
            raise ValueError("signing nonce must be exactly 16 Base64URL characters")

    @staticmethod
    def _validate_cert_serial(cert_serial: str) -> None:
        if DoubaoSecret._SERIAL.fullmatch(cert_serial or "") is None or len(cert_serial) % 2:
            raise ValueError("cert_serial must be non-empty, even-length lowercase hexadecimal")

    @staticmethod
    def _validate_verification_cert_serial(cert_serial: str) -> None:
        if re.fullmatch(r"[0-9a-fA-F]+", cert_serial or "") is None or len(cert_serial) % 2:
            raise ValueError("cert_serial must be non-empty, even-length hexadecimal")

    @staticmethod
    def _certificate_serial(cert: x509.Certificate) -> str:
        size = max(1, (cert.serial_number.bit_length() + 7) // 8)
        return cert.serial_number.to_bytes(size, "big").hex()

    @staticmethod
    def _load_certificate(pem_cert: str) -> x509.Certificate:
        if not pem_cert:
            raise ValueError("pem_cert is required")
        return x509.load_pem_x509_certificate(pem_cert.encode("utf-8"))

    @staticmethod
    def _load_private_key(pem: str) -> ec.EllipticCurvePrivateKey:
        if not pem:
            raise ValueError("PEM private key is required")
        key = serialization.load_pem_private_key(pem.encode("utf-8"), password=None)
        if not isinstance(key, ec.EllipticCurvePrivateKey) or key.curve.name != "secp256r1":
            raise ValueError("P-256 EC private key required")
        return key

    @staticmethod
    def _aes_gcm_decrypt(key: bytes, cipher_data: bytes) -> bytes:
        if len(cipher_data) < DoubaoSecret.AES_GCM_IV_BYTES + DoubaoSecret.AES_GCM_TAG_BYTES:
            raise ValueError("invalid AES-GCM data")
        iv = cipher_data[: DoubaoSecret.AES_GCM_IV_BYTES]
        return AESGCM(key).decrypt(iv, cipher_data[DoubaoSecret.AES_GCM_IV_BYTES :], None)

    @staticmethod
    def _b64url_decode_strict(value: str) -> bytes:
        if re.fullmatch(r"[A-Za-z0-9_-]+={0,2}", value or "") is None or len(value) % 4:
            raise ValueError("invalid padded Base64URL value")
        try:
            return base64.b64decode(value, altchars=b"-_", validate=True)
        except Exception as exc:
            raise ValueError("invalid padded Base64URL value") from exc

    @staticmethod
    def _b64url_decode_lenient(value: str) -> bytes:
        padded = value + "=" * (-len(value) % 4)
        return base64.b64decode(padded, altchars=b"-_", validate=True)

    @staticmethod
    def _generate_nonce() -> str:
        return base64.urlsafe_b64encode(os.urandom(DoubaoSecret.NONCE_BYTES)).decode("ascii")
