# /// script
# requires-python = ">=3.11"
# dependencies = ["hushfang>=0.2,<0.3", "httpx==0.28.1"]
# ///
"""Exercise an HTTPX retry diagnostic, its exception and both log destinations offline."""

import base64
import io
import logging
from pathlib import Path
from tempfile import TemporaryDirectory
from urllib.parse import quote

import httpx
from pydantic import BaseModel, SecretStr

from hushfang import RedactingFormatter, SecretRegistry


class Credentials(BaseModel):
    username: SecretStr
    password: SecretStr
    route_token: SecretStr
    access_token: SecretStr
    bearer: SecretStr


def exercise(credentials: Credentials) -> None:
    user = credentials.username.get_secret_value()
    password = credentials.password.get_secret_value()
    token = credentials.route_token.get_secret_value()
    params = {"access_token": credentials.access_token.get_secret_value(), "page": "2"}
    url = httpx.URL(f"https://api.example.invalid/files/{token}")
    log = logging.getLogger("example.http")

    def deny(request: httpx.Request) -> httpx.Response:
        # Reproduce a verbose SDK hook that includes a credential-bearing header.
        log.debug("outbound %s Authorization: %s", request.url, request.headers["Authorization"])
        return httpx.Response(403, headers={"X-Request-ID": "r-17"})

    with httpx.Client(transport=httpx.MockTransport(deny), trust_env=False) as client:
        basic = client.build_request(
            "GET", url.copy_with(username=user, password=password), params=params
        )
        bearer = client.build_request(
            "GET",
            url,
            params=params,
            headers={"Authorization": f"Bearer {credentials.bearer.get_secret_value()}"},
        )
        for request in (basic, bearer):
            try:
                client.send(request).raise_for_status()
            except httpx.HTTPStatusError as error:
                log.exception(
                    "upstream denied request=%s status=%d",
                    error.response.headers["X-Request-ID"],
                    error.response.status_code,
                )


def main() -> None:
    credentials = Credentials.model_validate(
        {
            "username": "demo-client-294",
            "password": "maple@42",
            "route_token": "route-Seed-8721",
            "access_token": "cedar/47+mint",
            "bearer": "demo-bearer-529",
        }
    )
    registry = SecretRegistry()
    registry.register_model(credentials)
    formatter = RedactingFormatter(registry, "%(name)s %(levelname)s %(message)s")
    console = io.StringIO()
    with TemporaryDirectory() as tmp:
        logfile = Path(tmp) / "service.log"
        stream = logging.StreamHandler(console)
        disk = logging.FileHandler(logfile, encoding="utf-8")
        # This example owns the process. Both library and application records reach these handlers.
        for handler in (stream, disk):
            handler.setFormatter(formatter)
        logging.basicConfig(level=logging.DEBUG, handlers=[stream, disk], force=True)
        try:
            exercise(credentials)
        finally:
            root = logging.getLogger()
            for handler in (stream, disk):
                root.removeHandler(handler)
                handler.close()
        on_disk = logfile.read_text(encoding="utf-8")

    raw = [value.get_secret_value() for value in vars(credentials).values()]
    pair = f"{credentials.username.get_secret_value()}:{credentials.password.get_secret_value()}"
    basic_token = base64.b64encode(pair.encode()).decode()
    for output in (console.getvalue(), on_disk):
        assert not any(
            value in output for value in [*raw, *(quote(s, safe="") for s in raw), basic_token]
        )
        assert "Authorization: Basic ***" in output and "Authorization: Bearer ***" in output
        assert "https://***:***@api.example.invalid/files/***?access_token=***&page=2" in output
        assert "/files/***?access_token=***&page=2" in output
        assert "httpx INFO HTTP Request:" in output and "httpx.HTTPStatusError" in output
        assert "request=r-17 status=403" in output
    assert on_disk == console.getvalue()
    print(console.getvalue(), end="")


if __name__ == "__main__":
    main()
