import uuid
import pytest
from httpx import AsyncClient
from sqlalchemy import text, select
from sqlalchemy.ext.asyncio import AsyncSession
from core.rate_limit import RateLimiter, rate_limiter
from core.security.files import secure_filename, validate_file_content
from core.exceptions import ValidationError
from modules.audit.service import AuditService
from modules.audit.models import AuditLog
from modules.message_studio.renderer import TemplateRenderer
from modules.tenants.models import Tenant


@pytest.mark.unit
def test_secure_filename_and_path_traversal_neutralization():
    # 1. Directory traversal attacks
    assert secure_filename("../../etc/passwd") == "passwd"
    assert secure_filename("..\\..\\windows\\system32\\cmd.exe") == "cmd.exe"
    assert secure_filename("/var/www/uploads/shell.php") == "shell.php"
    assert secure_filename("normal_avatar.png") == "normal_avatar.png"
    assert secure_filename("null\x00byte.jpg") == "nullbyte.jpg"


@pytest.mark.unit
def test_validate_file_content_magic_bytes_and_extensions():
    # Valid PNG image with real PNG magic header (\x89PNG\r\n\x1a\n)
    valid_png_content = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
    safe_name = validate_file_content("avatar.png", valid_png_content, allowed_extensions={"png", "jpg"})
    assert safe_name == "avatar.png"

    # Spoofed extension: text/executable file named .png
    fake_png_content = b"<?php echo 'malicious_code'; ?>"
    with pytest.raises(ValidationError) as exc:
        validate_file_content("malicious.png", fake_png_content, allowed_extensions={"png"})
    assert "binary format" in str(exc.value)

    # Disallowed executable extension (.sh, .exe, .py)
    with pytest.raises(ValidationError) as exc:
        validate_file_content("payload.sh", b"#!/bin/bash\necho pwned", allowed_extensions={"png", "jpg"})
    assert "not permitted" in str(exc.value)

    # File size limit enforcement
    huge_content = b"A" * (11 * 1024 * 1024)
    with pytest.raises(ValidationError) as exc:
        validate_file_content("huge.png", huge_content, max_size_bytes=10 * 1024 * 1024)
    assert "maximum allowed size" in str(exc.value)


@pytest.mark.unit
def test_safe_template_rendering_zero_ssti_and_eval():
    # Verify that variable interpolation only interpolates known variables and NEVER evaluates expressions
    template = "Hello {first_name}! Your total is {amount}. Code: {{ 7 * 7 }} and {__import__('os').system('id')}"

    rendered = TemplateRenderer.interpolate_text(
        template_text=template,
        variables={
            "first_name": "Alice",
            "amount": "₹499",
        },
    )

    # Alice and ₹499 replaced
    assert "Hello Alice!" in rendered
    assert "total is ₹499" in rendered

    # Dangerous expressions must NOT be evaluated
    assert "49" not in rendered or "{{ 7 * 7 }}" in rendered  # Not evaluated as Python code 49
    assert "{__import__('os').system('id')}" in rendered  # Left unchanged, not executed


@pytest.mark.unit
def test_in_app_rate_limiter_sliding_window():
    limiter = RateLimiter()
    limiter.reset()

    test_ip = "203.0.113.42"
    path = "/api/v1/auth/login"  # Policy: limit 10, window 60s

    # Send 10 requests -> all permitted
    for _ in range(10):
        is_limited, limit, remaining, retry_after = limiter.is_rate_limited(test_ip, path)
        assert is_limited is False
        assert limit == 10

    # 11th request -> blocked
    is_limited, limit, remaining, retry_after = limiter.is_rate_limited(test_ip, path)
    assert is_limited is True
    assert remaining == 0
    assert retry_after > 0


@pytest.mark.asyncio
async def test_sql_injection_defense_via_parameterized_queries(db_session: AsyncSession):
    # Attempt classic SQL injection: ' OR '1'='1
    malicious_input = "' OR '1'='1"

    # Query using SQLAlchemy 2.0 parameterized select
    stmt = select(Tenant).where(Tenant.name == malicious_input)
    res = await db_session.execute(stmt)
    result = res.scalars().all()

    # Returns empty list, query was safely parameterized without syntax error or leakage
    assert len(result) == 0


@pytest.mark.asyncio
async def test_audit_service_action_logging(db_session: AsyncSession):
    tenant = Tenant(
        name="Security Audit Tenant",
        slug=f"audit-tenant-{uuid.uuid4().hex[:8]}",
        status="active",
    )
    db_session.add(tenant)
    await db_session.flush()

    audit_service = AuditService(db_session)

    log_entry = await audit_service.log_action(
        tenant_id=tenant.id,
        action="SECURITY_KEY_ROTATION",
        resource="vault:token_v1",
        ip_address="192.0.2.1",
        details={"key_version": 2, "actor": "admin"},
    )
    await db_session.commit()

    assert log_entry.id is not None
    assert log_entry.tenant_id == tenant.id
    assert log_entry.action == "SECURITY_KEY_ROTATION"
    assert log_entry.ip_address == "192.0.2.1"
    assert log_entry.details["key_version"] == 2
