# -*- coding: utf-8 -*-
"""Тест логов и JSON-записи: библиотека requests."""
import requests
import urllib3

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

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

OUTPUT_DIR = "output/test_requests"

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

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


class ApiClient:

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

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

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

    @request_logging(save_errors_to_file=True, errors_output_dir=OUTPUT_DIR)
    @validate_response(validator=validator_ok)
    def post_json(self):
        return requests.post(
            "https://httpbin.org/status/500",
            json={"login": "test", "password": "123"},
            verify=False,
        )


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

    # 1. Успешный запрос
    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 → AuthErrorCreds (через when_all)
    try:
        r = client.get_403()
    except Exceptions.Auth.ErrorCreds as e:
        print(f"[ERR] {type(e).__name__}: {e}")

    # 4. POST с телом → 500, проверяем что request_body записался
    try:
        r = client.post_json()
    except Exception as e:
        print(f"[ERR] {type(e).__name__}: {e}")

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