# -*- coding: utf-8 -*-
"""Тест логов и JSON-записи: библиотека tls_client."""
try:
    import tls_client
except ImportError:
    print("tls_client не установлен. Установите: pip install tls-client")
    raise SystemExit(1)

from src.request_pydantic_decorator import (
    validate_response,
    request_logging,
    ResponseValidator,
    Exceptions,
    status_code_is,
)

OUTPUT_DIR = "output/test_tls_client"

validator_ok = ResponseValidator().status_code().whitelist([200])

validator_auth = (
    ResponseValidator()
    .when_all(status_code_is(403), raise_as=Exceptions.Auth.AccountBanned)
    .status_code().whitelist([200])
)


class ApiClient:

    def __init__(self):
        self.session = tls_client.Session(
            client_identifier="chrome_120",
            random_tls_extension_order=True,
        )

    @request_logging(save_errors_to_file=True, errors_output_dir=OUTPUT_DIR)
    @validate_response(validator=validator_ok)
    def get_ok(self):
        res = self.session.get("https://httpbin.org/status/200")
        return self.session.get("https://httpbin.org/status/200")

    @request_logging(save_errors_to_file=True, errors_output_dir=OUTPUT_DIR)
    @validate_response(validator=validator_ok)
    def get_500(self):
        return self.session.get("https://httpbin.org/status/500")

    @request_logging(save_errors_to_file=True, errors_output_dir=OUTPUT_DIR)
    @validate_response(validator=validator_auth)
    def get_403(self):
        return self.session.get("https://httpbin.org/status/403")

    @request_logging(save_errors_to_file=True, errors_output_dir=OUTPUT_DIR)
    @validate_response(validator=validator_ok)
    def post_json(self):
        return self.session.post(
            "https://httpbin.org/status/500",
            json={"email": "test@mail.ru", "pass": "secret"},
        )


if __name__ == "__main__":
    client = ApiClient()
    print("=== tls_client ===\n")

    # 1. OK
    try:
        r = client.get_ok()
        print(f"[OK]  {r.response.status_code} {r.response.url}")
    except Exception as e:
        print(f"[ERR] {type(e).__name__}: {e}")

    # 2. 500 → StatusCodeError
    try:
        r = client.get_500()
    except Exceptions.Validation.StatusCode as e:
        print(f"[ERR] {type(e).__name__}: {e}")

    # 3. 403 → AccountBanned
    try:
        r = client.get_403()
    except Exceptions.Auth.AccountBanned as e:
        print(f"[ERR] {type(e).__name__}: {e}")

    # 4. POST 500
    try:
        r = client.post_json()
    except Exception as e:
        print(f"[ERR] {type(e).__name__}: {e}")

    print(f"\nJSON-файлы ошибок: {OUTPUT_DIR}/")
