"""
Integration tests for Deployment module
Tests Docker, CI/CD, and deployment utilities

Auto-generated by RapidKit - Deployment Module
Framework: {{ framework }}
Runtime: {{ runtime }}
"""

import importlib
import importlib.util
from pathlib import Path

import pytest


pytestmark = [pytest.mark.integration, pytest.mark.template_integration]


def test_dockerfile_exists():
    """Test that Dockerfile is generated"""
    dockerfile = Path("Dockerfile")

    if not dockerfile.exists():
        pytest.skip("Dockerfile not generated for this project")

    content = dockerfile.read_text(encoding="utf-8")

    # Basic Dockerfile checks
    assert "FROM" in content
    assert "python" in content.lower() or "node" in content.lower()


def test_docker_compose_exists():
    """Test that docker-compose.yml is generated"""
    compose_file = Path("docker-compose.yml")

    if not compose_file.exists():
        pytest.skip("docker-compose.yml not generated for this project")

    content = compose_file.read_text(encoding="utf-8")

    # Basic docker-compose checks
    assert "version:" in content or "services:" in content
    assert "image:" in content or "build:" in content


def test_compose_overlays_exist():
    """Verify modular Compose overlays are rendered"""

    compose_dir = Path("deploy/compose")
    if not compose_dir.exists():
        pytest.skip("compose overlays not generated for this project")

    expected = {"base.yml", "local.yml", "production.yml"}
    present = {path.name for path in compose_dir.glob("*.yml")}

    missing = expected - present
    assert not missing, f"Missing compose overlays: {sorted(missing)}"


def test_dockerignore_exists():
    """Test that .dockerignore is generated"""
    dockerignore = Path(".dockerignore")

    if not dockerignore.exists():
        pytest.skip(".dockerignore not generated for this project")

    content = dockerignore.read_text(encoding="utf-8")

    # Common dockerignore patterns
    assert any(
        pattern in content
        for pattern in [
            "__pycache__",
            "*.pyc",
            ".git",
            "node_modules",
            ".env",
        ]
    )


def test_github_workflows_exists():
    """Test that GitHub Actions workflows are generated"""
    workflows_dir = Path(".github/workflows")

    if not workflows_dir.exists():
        pytest.skip("GitHub workflows not generated for this project")

    workflow_files = list(workflows_dir.glob("*.yml")) + list(
        workflows_dir.glob("*.yaml")
    )

    assert len(workflow_files) > 0, "No workflow files found"

    # Check at least one workflow has basic CI structure
    for workflow_file in workflow_files:
        content = workflow_file.read_text(encoding="utf-8")
        if "on:" in content and ("push:" in content or "pull_request:" in content):
            assert "jobs:" in content
            break
    else:
        pytest.fail("No valid GitHub workflow found")


def test_makefile_exists():
    """Test that Makefile is generated"""
    makefile = Path("Makefile")

    if not makefile.exists():
        pytest.skip("Makefile not generated for this project")

    content = makefile.read_text(encoding="utf-8")

    # Common make targets
    common_targets = ["help", "test", "lint", "format", "clean", "build"]
    found_targets = [target for target in common_targets if f"{target}:" in content]

    assert len(found_targets) > 0, "No common make targets found"


def test_deployment_scripts_structure():
    """Test deployment scripts directory structure"""
    scripts_dir = Path("scripts")

    if not scripts_dir.exists():
        pytest.skip("Scripts directory not generated")

    # Check for common deployment scripts
    common_scripts = [
        "deploy.sh",
        "start.sh",
        "stop.sh",
        "health-check.sh",
    ]

    existing_scripts = [
        script for script in common_scripts if (scripts_dir / script).exists()
    ]

    # At least some deployment scripts should exist
    assert len(existing_scripts) > 0, "No deployment scripts found"


def test_environment_template():
    """Test environment template file"""
    env_example = Path(".env.example")

    if not env_example.exists():
        env_example = Path("env.example")

    if not env_example.exists():
        pytest.skip("Environment template not generated")

    content = env_example.read_text(encoding="utf-8")

    # Should have environment variable examples
    assert "=" in content
    assert len(content.strip()) > 0


def test_readme_deployment_section():
    """Test README has deployment section"""
    readme = Path("README.md")

    if not readme.exists():
        pytest.skip("README not found")

    content = readme.read_text(encoding="utf-8").lower()

    # Should mention deployment somewhere
    deployment_keywords = [
        "deploy",
        "docker",
        "container",
        "production",
        "hosting",
    ]

    found = any(keyword in content for keyword in deployment_keywords)
    assert found, "README should mention deployment"


@pytest.mark.skipif(
    importlib.util.find_spec("fastapi") is None,
    reason="FastAPI not installed",
)
def test_deployment_health_router_registration():
    """Ensure the deployment health router exposes the expected path"""
    from fastapi import FastAPI

    deployment_health = importlib.import_module(
        "src.health.deployment"
    )
    register_deployment_health = deployment_health.register_deployment_health  # type: ignore[attr-defined]

    app = FastAPI()
    register_deployment_health(app)

    paths = {route.path for route in app.routes}
    assert "/api/health/module/deployment" in paths


@pytest.mark.skipif(
    importlib.util.find_spec("fastapi") is None,
    reason="FastAPI not installed",
)
def test_deployment_health_endpoint_payload():
    """Invoke the deployment health endpoint and validate its payload"""
    from fastapi import FastAPI, status
    from fastapi.testclient import TestClient

    deployment_health = importlib.import_module(
        "src.health.deployment"
    )
    register_deployment_health = deployment_health.register_deployment_health  # type: ignore[attr-defined]

    app = FastAPI()
    register_deployment_health(app)

    client = TestClient(app)
    response = client.get("/api/health/module/deployment")

    assert response.status_code == status.HTTP_200_OK
    payload = response.json()
    assert payload["status"] == "ok"
    assert payload["module"] == "deployment"
    assert payload["runtime"] == "{{ runtime }}"


def test_deployment_config_files():
    """Test various deployment configuration files"""
    config_files = [
        "Dockerfile",
        "docker-compose.yml",
        ".dockerignore",
        "Makefile",
    ]

    existing_files = [f for f in config_files if Path(f).exists()]

    # At least some deployment files should exist
    assert len(existing_files) > 0, (
        f"No deployment configuration files found. "
        f"Expected at least one of: {config_files}"
    )


def test_gitignore_deployment_entries():
    """Test .gitignore has deployment-related entries"""
    gitignore = Path(".gitignore")

    if not gitignore.exists():
        pytest.skip(".gitignore not found")

    content = gitignore.read_text(encoding="utf-8")

    # Should ignore common deployment artifacts
    deployment_patterns = [
        "*.log",
        ".env",
        "dist",
        "build",
    ]

    found = [pattern for pattern in deployment_patterns if pattern in content]
    assert len(found) > 0, "gitignore should have deployment-related patterns"
