from __future__ import annotations

import json
from urllib.parse import urlsplit

import pytest

from scripts.production_smoke import (
    HttpSnapshot,
    SmokeConfig,
    SmokeFailure,
    normalize_base_url,
    normalize_revision,
    run_smoke,
    validate_bundle,
    validate_config,
    validate_health,
    validate_index,
    validate_robots,
)


BASE_URL = "https://fse3d.engfelix.com.br"
REVISION = "R2.17"
SECURITY_HEADERS = {
    "strict-transport-security": "max-age=31536000",
    "content-security-policy": "default-src 'self'; object-src 'none'",
    "x-content-type-options": "nosniff",
    "x-frame-options": "DENY",
}


def _snapshot(
    path: str,
    body: bytes,
    *,
    content_type: str,
    cache_control: str = "no-store, no-cache, must-revalidate, max-age=0",
    elapsed_seconds: float = 0.012,
) -> HttpSnapshot:
    url = f"{BASE_URL}{path}"
    return HttpSnapshot(
        requested_url=url,
        final_url=url,
        status=200,
        headers={
            **SECURITY_HEADERS,
            "content-type": content_type,
            "cache-control": cache_control,
        },
        body=body,
        elapsed_seconds=elapsed_seconds,
    )


def _config() -> SmokeConfig:
    return SmokeConfig(base_url=BASE_URL, expected_revision=REVISION)


def test_normalizers_refuse_insecure_ambiguous_or_credentialed_targets() -> None:
    assert normalize_base_url(f"{BASE_URL}/") == BASE_URL
    assert normalize_revision(" r2.17 ") == REVISION

    for unsafe in (
        "http://fse3d.engfelix.com.br",
        "https://user:secret@fse3d.engfelix.com.br",
        "https://fse3d.engfelix.com.br/api/health",
        "https://fse3d.engfelix.com.br?token=secret",
        "https://fse3d.engfelix.com.br:8443",
        "https://fse3d.engfelix.com.br:invalid",
    ):
        with pytest.raises(SmokeFailure):
            normalize_base_url(unsafe)
    with pytest.raises(SmokeFailure):
        normalize_revision("2.17")


def test_independent_response_validators_accept_the_public_contract() -> None:
    config = _config()
    index = _snapshot(
        "/",
        (
            '<!doctype html><link rel="stylesheet" '
            'href="/static/styles.css?v=R2.17">'
            '<script type="module" src="/static/app.js?v=R2.17"></script>'
        ).encode(),
        content_type="text/html; charset=utf-8",
    )
    health = _snapshot(
        "/api/health",
        json.dumps(
            {"status": "ok", "checks": {"database": True, "openseespy": True}}
        ).encode(),
        content_type="application/json",
    )
    public_config = _snapshot(
        "/api/config",
        json.dumps(
            {
                "auth_required": True,
                "docs_enabled": False,
                "calculation_jobs_enabled": True,
                "solver_engines": [{"id": "openseespy", "status": "available"}],
            }
        ).encode(),
        content_type="application/json; charset=utf-8",
    )
    robots = _snapshot(
        "/robots.txt",
        b"User-agent: *\nDisallow: /api/\nDisallow: /static/\n",
        content_type="text/plain; charset=utf-8",
    )
    bundle = _snapshot(
        "/static/app.js?v=R2.17",
        b'import "./api.js?v=R2.17";\nconst APP_REVISION = "R2.17";\n',
        content_type="text/javascript; charset=utf-8",
        cache_control="public, max-age=31536000, immutable",
    )

    assert REVISION in validate_index(index, config)
    assert "OpenSeesPy" in validate_health(health, config)
    assert "OpenSeesPy" in validate_config(public_config, config)
    assert "crawlers" in validate_robots(robots, config)
    assert REVISION in validate_bundle(bundle, config)


def test_validators_fail_closed_for_stale_or_degraded_responses() -> None:
    config = _config()
    stale_index = _snapshot(
        "/",
        (
            '<link rel="stylesheet" href="/static/styles.css?v=R2.16">'
            '<script src="/static/app.js?v=R2.16"></script>'
        ).encode(),
        content_type="text/html",
    )
    degraded_health = _snapshot(
        "/api/health",
        b'{"status":"ok","checks":{"database":true,"openseespy":false}}',
        content_type="application/json",
    )
    stale_bundle = _snapshot(
        "/static/app.js?v=R2.17",
        b'const APP_REVISION = "R2.16";',
        content_type="text/javascript",
        cache_control="public, max-age=31536000, immutable",
    )
    leaked_placeholder = _snapshot(
        "/static/app.js?v=R2.17",
        b'const APP_REVISION = "__APP_REVISION__";',
        content_type="text/javascript",
        cache_control="public, max-age=31536000, immutable",
    )

    with pytest.raises(SmokeFailure):
        validate_index(stale_index, config)
    with pytest.raises(SmokeFailure):
        validate_health(degraded_health, config)
    with pytest.raises(SmokeFailure):
        validate_bundle(stale_bundle, config)
    with pytest.raises(SmokeFailure):
        validate_bundle(leaked_placeholder, config)


def test_runner_uses_only_fixed_public_get_targets_and_records_timings() -> None:
    requested: list[str] = []

    def fake_fetcher(url: str, timeout_seconds: float, max_body_bytes: int) -> HttpSnapshot:
        assert timeout_seconds == 15.0
        assert max_body_bytes == 2_000_000
        requested.append(url)
        path = urlsplit(url).path
        if path == "/":
            return _snapshot(
                "/",
                (
                    '<link rel="stylesheet" href="/static/styles.css?v=R2.17">'
                    '<script src="/static/app.js?v=R2.17"></script>'
                ).encode(),
                content_type="text/html",
            )
        if path == "/api/health":
            return _snapshot(
                path,
                b'{"status":"ok","checks":{"database":true,"openseespy":true}}',
                content_type="application/json",
            )
        if path == "/api/config":
            return _snapshot(
                path,
                json.dumps(
                    {
                        "auth_required": True,
                        "docs_enabled": False,
                        "calculation_jobs_enabled": True,
                        "solver_engines": [
                            {"id": "openseespy", "status": "available"}
                        ],
                    }
                ).encode(),
                content_type="application/json",
            )
        if path == "/robots.txt":
            return _snapshot(
                path,
                b"User-agent: *\nDisallow: /api/\nDisallow: /static/\n",
                content_type="text/plain",
            )
        assert path == "/static/app.js"
        return _snapshot(
            "/static/app.js?v=R2.17",
            b'const APP_REVISION = "R2.17";',
            content_type="text/javascript",
            cache_control="public, max-age=31536000, immutable",
        )

    report = run_smoke(_config(), fetcher=fake_fetcher)

    assert report.passed
    assert len(report.checks) == 5
    assert all(check.elapsed_seconds == 0.012 for check in report.checks)
    assert requested == [
        f"{BASE_URL}/",
        f"{BASE_URL}/api/health",
        f"{BASE_URL}/api/config",
        f"{BASE_URL}/robots.txt",
        f"{BASE_URL}/static/app.js?v=R2.17",
    ]
    assert all(urlsplit(url).scheme == "https" for url in requested)


def test_runner_rejects_redirects_and_missing_security_headers() -> None:
    calls = 0

    def invalid_fetcher(url: str, timeout_seconds: float, max_body_bytes: int) -> HttpSnapshot:
        del timeout_seconds, max_body_bytes
        nonlocal calls
        calls += 1
        snapshot = _snapshot(
            urlsplit(url).path,
            b"{}",
            content_type="application/json",
            elapsed_seconds=0.200,
        )
        if calls == 1:
            return HttpSnapshot(
                **{
                    **snapshot.__dict__,
                    "final_url": "https://other.example/",
                }
            )
        return HttpSnapshot(
            **{
                **snapshot.__dict__,
                "headers": {"content-type": "application/json"},
            }
        )

    report = run_smoke(
        SmokeConfig(
            base_url=BASE_URL,
            expected_revision=REVISION,
            max_response_seconds=0.100,
        ),
        fetcher=invalid_fetcher,
    )

    assert not report.passed
    assert len(report.checks) == 5
    assert all(not check.passed for check in report.checks)
    assert "Redirect" in report.checks[0].detail
    assert "seguranca" in report.checks[1].detail


def test_runner_fails_a_valid_contract_that_exceeds_the_time_budget() -> None:
    def slow_fetcher(url: str, timeout_seconds: float, max_body_bytes: int) -> HttpSnapshot:
        del timeout_seconds, max_body_bytes
        path = urlsplit(url).path
        if path == "/":
            return _snapshot(
                path,
                (
                    '<link rel="stylesheet" href="/static/styles.css?v=R2.17">'
                    '<script src="/static/app.js?v=R2.17"></script>'
                ).encode(),
                content_type="text/html",
                elapsed_seconds=0.200,
            )
        if path == "/api/health":
            return _snapshot(
                path,
                b'{"status":"ok","checks":{"database":true,"openseespy":true}}',
                content_type="application/json",
                elapsed_seconds=0.200,
            )
        if path == "/api/config":
            return _snapshot(
                path,
                json.dumps(
                    {
                        "auth_required": True,
                        "docs_enabled": False,
                        "calculation_jobs_enabled": True,
                        "solver_engines": [
                            {"id": "openseespy", "status": "available"}
                        ],
                    }
                ).encode(),
                content_type="application/json",
                elapsed_seconds=0.200,
            )
        if path == "/robots.txt":
            return _snapshot(
                path,
                b"User-agent: *\nDisallow: /api/\nDisallow: /static/\n",
                content_type="text/plain",
                elapsed_seconds=0.200,
            )
        return _snapshot(
            "/static/app.js?v=R2.17",
            b'const APP_REVISION = "R2.17";',
            content_type="text/javascript",
            cache_control="public, max-age=31536000, immutable",
            elapsed_seconds=0.200,
        )

    report = run_smoke(
        SmokeConfig(
            base_url=BASE_URL,
            expected_revision=REVISION,
            max_response_seconds=0.100,
        ),
        fetcher=slow_fetcher,
    )

    assert not report.passed
    assert all(not check.passed for check in report.checks)
    assert all("excede" in check.detail for check in report.checks)
