from __future__ import annotations

import asyncio
from http.cookies import SimpleCookie
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

from fastapi import FastAPI, HTTPException, Request, Response
from pydantic import ValidationError
from sqlalchemy import create_engine, func, select
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from app import security
from app.auth_routes import login, register, router as auth_router
from app.database import Base, get_db
from app.models import User, UserSession
from app.preferences import sanitize_preference_overrides, validate_preference_patch
from app.rate_limit import RateLimitStoreError, SQLiteRateLimitStore
from app.schemas import LoginRequest, RegisterRequest
from scripts.manage_admin import _generated_password


def request_for(
    ip: str = "198.51.100.10",
    *,
    csrf: bool = True,
    forwarded_for: str = "",
) -> Request:
    headers = [(b"user-agent", b"FSE3D security test")]
    if csrf:
        headers.extend(
            [
                (b"cookie", b"fse3d_csrf=test-csrf-token"),
                (b"x-fse3d-csrf", b"test-csrf-token"),
            ]
        )
    if forwarded_for:
        headers.append((b"x-forwarded-for", forwarded_for.encode("ascii")))
    return Request(
        {
            "type": "http",
            "method": "POST",
            "scheme": "https",
            "path": "/api/auth/login",
            "query_string": b"",
            "headers": headers,
            "client": (ip, 43210),
            "server": ("fse3d.test", 443),
        }
    )


async def call_auth_asgi(
    app: FastAPI,
    method: str,
    path: str,
    payload: dict,
    cookies: dict[str, str],
    csrf_token: str,
) -> tuple[int, list[tuple[bytes, bytes]], bytes]:
    body = json.dumps(payload).encode("utf-8")
    cookie_header = "; ".join(f"{name}={value}" for name, value in cookies.items())
    headers = [
        (b"host", b"fse3d.test"),
        (b"content-type", b"application/json"),
        (b"content-length", str(len(body)).encode("ascii")),
        (b"cookie", cookie_header.encode("latin-1")),
        (b"x-fse3d-csrf", csrf_token.encode("ascii")),
        (b"user-agent", b"FSE3D security HTTP regression"),
    ]
    messages: list[dict] = []
    received = False
    scope = {
        "type": "http",
        "asgi": {"version": "3.0"},
        "http_version": "1.1",
        "method": method,
        "scheme": "https",
        "path": path,
        "raw_path": path.encode("ascii"),
        "query_string": b"",
        "headers": headers,
        "client": ("198.51.100.90", 43210),
        "server": ("fse3d.test", 443),
    }

    async def receive() -> dict:
        nonlocal received
        if not received:
            received = True
            return {"type": "http.request", "body": body, "more_body": False}
        return {"type": "http.disconnect"}

    async def send(message: dict) -> None:
        messages.append(message)

    await app(scope, receive, send)
    response_start = next(
        message for message in messages if message["type"] == "http.response.start"
    )
    response_body = b"".join(
        message.get("body", b"")
        for message in messages
        if message["type"] == "http.response.body"
    )
    return response_start["status"], response_start.get("headers", []), response_body


def apply_response_cookies(
    cookies: dict[str, str],
    headers: list[tuple[bytes, bytes]],
) -> None:
    for name, value in headers:
        if name.lower() != b"set-cookie":
            continue
        parsed = SimpleCookie()
        parsed.load(value.decode("latin-1"))
        for cookie_name, morsel in parsed.items():
            if morsel["max-age"] == "0" or not morsel.value:
                cookies.pop(cookie_name, None)
            else:
                cookies[cookie_name] = morsel.value


class SecurityContractsTests(unittest.TestCase):
    def setUp(self) -> None:
        self.engine = create_engine(
            "sqlite+pysqlite:///:memory:",
            connect_args={"check_same_thread": False},
            poolclass=StaticPool,
        )
        Base.metadata.create_all(self.engine)
        self.Session = sessionmaker(bind=self.engine, autoflush=False)
        self.db = self.Session()
        self.rate_limit_temp = tempfile.TemporaryDirectory()
        self.rate_limit_store = SQLiteRateLimitStore(
            Path(self.rate_limit_temp.name) / "security-rate-limit.sqlite3",
            max_keys=100,
        )
        self.rate_limit_patch = patch.object(
            security,
            "_rate_limit_store",
            self.rate_limit_store,
        )
        self.rate_limit_patch.start()
        self.http_app = FastAPI()
        self.http_app.include_router(auth_router)

        def override_db():
            http_db = self.Session()
            try:
                yield http_db
            finally:
                http_db.close()

        self.http_app.dependency_overrides[get_db] = override_db

    def tearDown(self) -> None:
        self.rate_limit_patch.stop()
        self.rate_limit_temp.cleanup()
        self.db.close()
        self.engine.dispose()

    def test_registration_requires_csrf_and_strong_password(self) -> None:
        with self.assertRaises(ValidationError):
            RegisterRequest(name="Teste", email="teste@example.com", password="somente-minusculas")

        payload = RegisterRequest(
            name="Usuario Teste",
            email="Usuario@Example.com",
            password="Senha-Forte-2026",
        )
        with self.assertRaises(HTTPException) as context:
            register(payload, request_for(csrf=False), Response(), self.db)
        self.assertEqual(context.exception.status_code, 403)

        result = register(payload, request_for(), Response(), self.db)
        self.assertEqual(result.user.email, "usuario@example.com")
        self.assertFalse(result.user.is_admin)
        persisted = self.db.execute(select(User).where(User.email == result.user.email)).scalar_one()
        self.assertTrue(security.verify_password(payload.password, persisted.password_hash))
        self.assertNotEqual(persisted.password_hash, payload.password)
        self.assertFalse(persisted.is_admin)

        with self.assertRaises(HTTPException) as duplicate:
            register(payload, request_for(ip="198.51.100.11"), Response(), self.db)
        self.assertEqual(duplicate.exception.status_code, 409)
        self.assertNotIn("email", str(duplicate.exception.detail).lower())

    def test_logout_rotates_csrf_and_allows_login_and_registration_without_reload(self) -> None:
        cookies = {security.CSRF_COOKIE_NAME: "initial-csrf-token"}

        def post(
            path: str,
            payload: dict,
            csrf_token: str | None = None,
        ) -> tuple[int, bytes]:
            token = csrf_token or cookies[security.CSRF_COOKIE_NAME]
            status_code, headers, body = asyncio.run(
                call_auth_asgi(self.http_app, "POST", path, payload, cookies, token)
            )
            apply_response_cookies(cookies, headers)
            return status_code, body

        account = {
            "name": "Usuario HTTP",
            "email": "http-login@example.com",
            "password": "Senha-Forte-HTTP-2026",
        }
        status_code, _ = post("/api/auth/register", account)
        self.assertEqual(status_code, 201)
        self.assertIn(security.SESSION_COOKIE_NAME, cookies)

        csrf_before_logout = cookies[security.CSRF_COOKIE_NAME]
        status_code, _ = post("/api/auth/logout", {})
        self.assertEqual(status_code, 200)
        self.assertNotIn(security.SESSION_COOKIE_NAME, cookies)
        csrf_after_logout = cookies[security.CSRF_COOKIE_NAME]
        self.assertNotEqual(csrf_after_logout, csrf_before_logout)

        status_code, _ = post(
            "/api/auth/login",
            {"email": account["email"], "password": account["password"]},
            csrf_token=csrf_before_logout,
        )
        self.assertEqual(status_code, 403)
        status_code, _ = post(
            "/api/auth/login",
            {"email": account["email"], "password": account["password"]},
        )
        self.assertEqual(status_code, 200)
        self.assertIn(security.SESSION_COOKIE_NAME, cookies)

        status_code, _ = post("/api/auth/logout", {})
        self.assertEqual(status_code, 200)
        self.assertNotIn(security.SESSION_COOKIE_NAME, cookies)
        status_code, _ = post(
            "/api/auth/register",
            {
                "name": "Nova Conta HTTP",
                "email": "http-register@example.com",
                "password": "Outra-Senha-HTTP-2026",
            },
        )
        self.assertEqual(status_code, 201)
        self.assertIn(security.SESSION_COOKIE_NAME, cookies)

    def test_admin_role_is_explicit_and_generated_password_is_strong(self) -> None:
        ordinary = User(
            account_uid="FSE-0000-0000-0001",
            name="Usuario",
            email="ordinary@example.com",
            password_hash="hash",
            is_admin=False,
        )
        with self.assertRaises(HTTPException) as forbidden:
            security.get_admin_user(ordinary)
        self.assertEqual(forbidden.exception.status_code, 403)

        admin = User(
            account_uid="FSE-0000-0000-0002",
            name="Administrador",
            email="admin@example.com",
            password_hash="hash",
            is_admin=True,
        )
        self.assertIs(security.get_admin_user(admin), admin)

        password = _generated_password()
        self.assertGreaterEqual(len(password), 28)
        self.assertTrue(any(char.islower() for char in password))
        self.assertTrue(any(char.isupper() for char in password))
        self.assertTrue(any(char.isdigit() for char in password))
        self.assertTrue(any(not char.isalnum() for char in password))

    def test_unknown_login_uses_dummy_hash_and_invalid_hash_fails_closed(self) -> None:
        payload = LoginRequest(email="ausente@example.com", password="qualquer")
        with patch("app.auth_routes.verify_password", return_value=False) as verify:
            with self.assertRaises(HTTPException) as context:
                login(payload, request_for(), Response(), self.db)
        self.assertEqual(context.exception.status_code, 401)
        used_hash = verify.call_args.args[1]
        self.assertTrue(used_hash.startswith("$argon2"))
        self.assertFalse(security.verify_password("senha", "hash-corrompido"))

    def test_session_count_and_rate_limiter_storage_are_bounded(self) -> None:
        user = User(
            account_uid="FSE-1111-2222-3333",
            name="Teste",
            email="session@example.com",
            password_hash=security.hash_password("Senha-Forte-2026"),
        )
        self.db.add(user)
        self.db.commit()
        self.db.refresh(user)

        for index in range(security.SESSION_MAX_ACTIVE + 3):
            security.create_user_session(self.db, user, request_for(ip=f"198.51.100.{index + 1}"))
        active_count = self.db.execute(
            select(func.count(UserSession.id)).where(
                UserSession.user_id == user.id,
                UserSession.revoked_at.is_(None),
            )
        ).scalar_one()
        self.assertLessEqual(active_count, security.SESSION_MAX_ACTIVE)

        bounded_store = SQLiteRateLimitStore(
            Path(self.rate_limit_temp.name) / "bounded-rate-limit.sqlite3",
            max_keys=3,
        )
        with patch.object(security, "_rate_limit_store", bounded_store):
            for index in range(4):
                if index < 3:
                    security.check_rate_limit(
                        request_for(ip=f"203.0.113.{index + 1}"),
                        "bounded-test",
                        10,
                        60,
                    )
                else:
                    with self.assertRaises(HTTPException) as capacity:
                        security.check_rate_limit(
                            request_for(ip=f"203.0.113.{index + 1}"),
                            "bounded-test",
                            10,
                            60,
                        )
                    self.assertEqual(capacity.exception.status_code, 429)
        self.assertEqual(bounded_store.entry_count(), 3)

    def test_rate_limiter_returns_retry_after_and_fails_closed(self) -> None:
        request = request_for(ip="203.0.113.80")
        security.check_rate_limit(request, "retry-test", 2, 60)
        security.check_rate_limit(request, "retry-test", 2, 60)
        with self.assertRaises(HTTPException) as limited:
            security.check_rate_limit(request, "retry-test", 2, 60)
        self.assertEqual(limited.exception.status_code, 429)
        self.assertGreaterEqual(int(limited.exception.headers["Retry-After"]), 1)

        with patch.object(
            self.rate_limit_store,
            "consume",
            side_effect=RateLimitStoreError("storage unavailable"),
        ):
            with self.assertRaises(HTTPException) as unavailable:
                security.check_rate_limit(
                    request_for(ip="203.0.113.81"),
                    "fail-closed-test",
                    2,
                    60,
                )
        self.assertEqual(unavailable.exception.status_code, 503)
        self.assertEqual(unavailable.exception.headers["Retry-After"], "1")

    def test_empty_rate_limit_path_uses_private_app_default(self) -> None:
        with patch.dict(
            security.os.environ,
            {"FSE3D_RATE_LIMIT_DB_PATH": ""},
        ):
            self.assertEqual(
                security._rate_limit_db_path(),
                security.APP_ROOT / "tmp" / "rate-limit" / "state.sqlite3",
            )

    def test_forwarded_client_uses_proxy_appended_value(self) -> None:
        request = request_for(
            ip="127.0.0.1",
            forwarded_for="127.0.0.1, 203.0.113.55",
        )
        self.assertEqual(security.client_ip(request), "203.0.113.55")

    def test_forwarded_client_skips_only_configured_proxy_networks(self) -> None:
        request = request_for(
            ip="127.0.0.1",
            forwarded_for="198.51.100.25, 203.0.113.55",
        )
        networks = (
            security.ipaddress.ip_network("127.0.0.0/8"),
            security.ipaddress.ip_network("203.0.113.0/24"),
        )
        with patch.object(security, "TRUSTED_PROXY_NETWORKS", networks):
            self.assertEqual(security.client_ip(request), "198.51.100.25")

        untrusted_peer = request_for(
            ip="192.0.2.10",
            forwarded_for="127.0.0.1",
        )
        self.assertEqual(security.client_ip(untrusted_peer), "192.0.2.10")

    def test_ipv4_mapped_proxy_and_client_are_normalized(self) -> None:
        request = request_for(
            ip="::ffff:127.0.0.1",
            forwarded_for="::ffff:198.51.100.25",
        )
        self.assertTrue(security.is_trusted_proxy(request))
        self.assertEqual(security.client_ip(request), "198.51.100.25")

    def test_preferences_drop_obsolete_values_and_reject_non_finite_numbers(self) -> None:
        sanitized = sanitize_preference_overrides(
            {"units": {"force": "kN"}, "viewer": {"visual": {"showGrid": True}}}
        )
        self.assertNotIn("units", sanitized)
        self.assertTrue(sanitized["viewer"]["visual"]["showGrid"])
        with self.assertRaisesRegex(ValueError, "finita"):
            validate_preference_patch({"viewer": {"visual": {"nodeSize": float("nan")}}})

        deeply_nested = {"value": True}
        for index in range(10):
            deeply_nested = {f"level{index}": deeply_nested}
        with self.assertRaisesRegex(ValueError, "profundidade"):
            validate_preference_patch(deeply_nested)

    def test_interface_preferences_accept_only_supported_themes(self) -> None:
        validate_preference_patch(
            {
                "interface": {
                    "appearance": {"theme": "metal"},
                    "panels": {"draggable": True},
                }
            }
        )
        with self.assertRaises(ValueError):
            validate_preference_patch(
                {"interface": {"appearance": {"theme": "arbitrary-css"}}}
            )


if __name__ == "__main__":
    unittest.main()
