import importlib
import ssl
from pathlib import Path

import pytest


http_client = importlib.import_module("gjalla_precommit.protocol.http_client")


def test_http_proxy_used(monkeypatch):
    monkeypatch.setenv("HTTP_PROXY", "http://proxy.local:8080")
    proxies = http_client.get_proxy_settings()
    assert proxies["http"] == "http://proxy.local:8080"


def test_https_proxy_used(monkeypatch):
    monkeypatch.setenv("HTTPS_PROXY", "https://secure-proxy.local:8443")
    proxies = http_client.get_proxy_settings()
    assert proxies["https"] == "https://secure-proxy.local:8443"


def test_no_proxy_respected(monkeypatch):
    monkeypatch.setenv("NO_PROXY", "gjalla.io,localhost")
    assert http_client.should_bypass_proxy("gjalla.io")


def test_insecure_flag_disables_ssl():
    context = http_client.build_ssl_context(insecure=True, ca_cert=None)
    assert context.verify_mode == ssl.CERT_NONE


def test_insecure_flag_shows_warning():
    assert "insecure" in http_client.describe_ssl_mode(insecure=True).lower()


def test_custom_ca_cert(tmp_path: Path):
    cert_path = tmp_path / "ca.pem"
    cert_path.write_text("-----BEGIN CERTIFICATE-----\nMIIB...fake\n-----END CERTIFICATE-----\n")
    context = http_client.build_ssl_context(insecure=False, ca_cert=cert_path)
    assert isinstance(context, ssl.SSLContext)
