# #region Test.Api.Environments [C:3] [TYPE Module] [SEMANTICS test,environments,api]
# @BRIEF Unit tests for environments API routes — list, schedule, databases.
# @RELATION BINDS_TO -> [EnvironmentsApi]
# @TEST_EDGE: environment_not_found -> 404
# @TEST_EDGE: empty_list -> 200 empty
# @TEST_EDGE: superset_connection_fail -> 500

import os

os.environ.setdefault("DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("AUTH_DATABASE_URL", "sqlite:///:memory:")
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-tests")

import sys
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

_src = str(Path(__file__).resolve().parent.parent.parent / "src")
if _src not in sys.path:
    sys.path.insert(0, _src)


def _make_mock_env(
    id: str = "env-1",
    name: str = "Production",
    url: str = "https://superset.example.com",
    stage: str = "PROD",
    is_production: bool = True,
    backup_enabled: bool = True,
    backup_cron: str = "0 0 * * *",
):
    env = MagicMock()
    env.id = id
    env.name = name
    env.url = url
    env.stage = stage
    env.is_production = is_production
    env.backup_schedule = MagicMock()
    env.backup_schedule.enabled = backup_enabled
    env.backup_schedule.cron_expression = backup_cron
    return env


def _make_client(overrides: dict | None = None) -> TestClient:
    from src.api.routes.environments import router
    from src.dependencies import get_current_user, has_permission
    from src.schemas.auth import User, RoleSchema

    app = FastAPI()
    app.include_router(router)

    mock_user = User(
        id="admin-1", username="admin", email="admin@x.com",
        auth_source="LOCAL",
        created_at=__import__("datetime").datetime.now(),
        roles=[RoleSchema(id="r1", name="Admin", description="", permissions=[])],
    )

    defaults = {
        get_current_user: lambda: mock_user,
    }
    if overrides:
        defaults.update(overrides)
    for dep, mock_fn in defaults.items():
        app.dependency_overrides[dep] = mock_fn
    return TestClient(app)


# ── get_environments ──

class TestGetEnvironments:
    """GET /api/environments"""

    def test_list_environments_success(self):
        """Happy path: returns list of environments."""
        mock_config = MagicMock()
        mock_config.get_environments.return_value = [
            _make_mock_env(id="env-1", name="Dev", url="https://dev.superset.example.com", stage="DEV", is_production=False),
            _make_mock_env(id="env-2", name="Prod", url="https://prod.superset.example.com/api/v1", stage="PROD", is_production=True),
        ]

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/environments")
        assert resp.status_code == 200
        data = resp.json()
        assert len(data) == 2
        assert data[0]["id"] == "env-1"
        assert data[0]["url"] == "https://dev.superset.example.com"
        assert data[0]["stage"] == "DEV"
        assert data[1]["stage"] == "PROD"
        assert data[1]["is_production"] is True

    def test_list_environments_not_a_list(self):
        """Non-list environments returns empty list."""
        mock_config = MagicMock()
        mock_config.get_environments.return_value = None

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/environments")
        assert resp.status_code == 200
        assert resp.json() == []

    def test_list_environments_empty(self):
        """Empty environments list returns 200 with empty array."""
        mock_config = MagicMock()
        mock_config.get_environments.return_value = []

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/environments")
        assert resp.status_code == 200
        assert resp.json() == []

    def test_list_environments_no_backup_schedule(self):
        """Environment without backup schedule returns None schedule."""
        env = _make_mock_env(backup_enabled=False)
        env.backup_schedule = None

        mock_config = MagicMock()
        mock_config.get_environments.return_value = [env]

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/environments")
        assert resp.status_code == 200
        assert resp.json()[0]["backup_schedule"] is None


# ── update_environment_schedule ──

class TestUpdateEnvironmentSchedule:
    """PUT /api/environments/{id}/schedule"""

    def test_update_schedule_success(self):
        """Happy path: schedule updated."""
        env = _make_mock_env(id="env-1")
        mock_config = MagicMock()
        mock_config.get_environments.return_value = [env]
        mock_scheduler = MagicMock()

        from src.dependencies import get_config_manager, get_scheduler_service
        client = _make_client({
            get_config_manager: lambda: mock_config,
            get_scheduler_service: lambda: mock_scheduler,
        })
        resp = client.put("/api/environments/env-1/schedule", json={
            "enabled": True,
            "cron_expression": "0 6 * * *",
        })
        assert resp.status_code == 200
        assert resp.json()["message"] == "Schedule updated successfully"
        assert env.backup_schedule.cron_expression == "0 6 * * *"
        mock_config.update_environment.assert_called_once_with("env-1", env)
        mock_scheduler.load_schedules.assert_called_once()

    def test_update_schedule_invalid_cron(self):
        """Invalid cron expression returns 422."""
        from src.dependencies import get_config_manager, get_scheduler_service
        client = _make_client({
            get_config_manager: lambda: MagicMock(),
            get_scheduler_service: lambda: MagicMock(),
        })
        resp = client.put("/api/environments/env-1/schedule", json={
            "enabled": True,
            "cron_expression": "not-a-cron",
        })
        assert resp.status_code == 422

    def test_update_schedule_env_not_found(self):
        """Non-existent environment returns 404."""
        mock_config = MagicMock()
        mock_config.get_environments.return_value = []

        from src.dependencies import get_config_manager, get_scheduler_service
        client = _make_client({
            get_config_manager: lambda: mock_config,
            get_scheduler_service: lambda: MagicMock(),
        })
        resp = client.put("/api/environments/env-999/schedule", json={
            "enabled": True,
            "cron_expression": "0 0 * * *",
        })
        assert resp.status_code == 404


# ── get_environment_databases ──

class TestGetEnvironmentDatabases:
    """GET /api/environments/{id}/databases"""

    def test_get_databases_success(self):
        """Happy path: returns database list."""
        env = _make_mock_env(id="env-1")
        mock_config = MagicMock()
        mock_config.get_environments.return_value = [env]

        mock_client = AsyncMock()
        mock_client.get_databases_summary.return_value = [
            {"uuid": "db-1", "database_name": "sales", "engine": "postgresql"},
        ]

        with patch("src.api.routes.environments.AsyncSupersetClient", return_value=mock_client):
            from src.dependencies import get_config_manager
            client = _make_client({get_config_manager: lambda: mock_config})
            resp = client.get("/api/environments/env-1/databases")
        assert resp.status_code == 200
        assert isinstance(resp.json(), list)
        assert resp.json()[0]["database_name"] == "sales"

    def test_get_databases_env_not_found(self):
        """Non-existent environment returns 404."""
        mock_config = MagicMock()
        mock_config.get_environments.return_value = []

        from src.dependencies import get_config_manager
        client = _make_client({get_config_manager: lambda: mock_config})
        resp = client.get("/api/environments/env-999/databases")
        assert resp.status_code == 404

    def test_get_databases_connection_fail(self):
        """Superset connection failure returns 500."""
        env = _make_mock_env(id="env-1")
        mock_config = MagicMock()
        mock_config.get_environments.return_value = [env]

        mock_client = AsyncMock()
        mock_client.get_databases_summary.side_effect = Exception("Connection refused")

        with patch("src.api.routes.environments.AsyncSupersetClient", return_value=mock_client):
            from src.dependencies import get_config_manager
            client = _make_client({get_config_manager: lambda: mock_config})
            resp = client.get("/api/environments/env-1/databases")
        assert resp.status_code == 500
        assert "Failed to fetch databases" in resp.text


# ── URL normalization ──

class TestNormalizeSupersetEnvUrl:
    """_normalize_superset_env_url"""

    def test_normalize_removes_api_v1(self):
        from src.api.routes.environments import _normalize_superset_env_url
        assert _normalize_superset_env_url("https://superset.example.com/api/v1") == "https://superset.example.com"

    def test_normalize_strips_trailing_slash(self):
        from src.api.routes.environments import _normalize_superset_env_url
        assert _normalize_superset_env_url("https://superset.example.com/") == "https://superset.example.com"

    def test_normalize_empty_string(self):
        from src.api.routes.environments import _normalize_superset_env_url
        assert _normalize_superset_env_url("") == ""

    def test_normalize_noop(self):
        from src.api.routes.environments import _normalize_superset_env_url
        assert _normalize_superset_env_url("https://superset.example.com") == "https://superset.example.com"
# #endregion Test.Api.Environments
