"""Provider registry and config persistence tests."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from app.services import runtime_config
from app.services.integrations import service as integrations_service
from app.services.integrations.registry import ProviderRegistry


@pytest.fixture()
def isolated_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    """Use a temporary runtime config path per test."""
    config_path = tmp_path / ".sentineledge" / "config.json"
    monkeypatch.setenv("SENTINELEDGE_CONFIG_PATH", str(config_path))
    runtime_config.reset_runtime_state()
    yield config_path
    runtime_config.reset_runtime_state()


def test_registry_status_and_defaults_from_provider_config(isolated_config: Path) -> None:
    """Registry should reflect enabled/configured providers and defaults."""
    providers = runtime_config.get_providers_snapshot()
    providers["github_issues"]["credentials"] = {"token": "github_token_placeholder"}
    providers["github_issues"]["settings"] = {"repo": "owner/repo"}
    providers["github_issues"]["enabled"] = True

    runtime_config.save_config(
        todoist_api_token=None,
        vault_paths=[],
        assistant_default_language="es",
        language_configured=False,
        providers=providers,
        default_task_provider="github_issues",
        default_notes_provider="vault_local",
        db=None,
    )

    registry = ProviderRegistry()
    statuses = registry.provider_statuses()
    assert statuses["github_issues"]["configured"] is True
    assert statuses["github_issues"]["enabled"] is True
    assert registry.default_task_provider() == "github_issues"
    assert "github_issues" in registry.enabled_task_provider_ids()


def test_provider_configs_are_independent_and_persisted(isolated_config: Path) -> None:
    """Saving one provider must not wipe others and should persist to disk."""
    _ = integrations_service.save_provider_config(
        provider_id="notion",
        enabled=True,
        credentials={"token": "notion_token_placeholder"},
        settings={"page_id": "page_123"},
        auth_mode="token",
        db=None,
    )
    _ = integrations_service.save_provider_config(
        provider_id="github_issues",
        enabled=True,
        credentials={"token": "github_token_placeholder"},
        settings={"repo": "owner/repo"},
        auth_mode="token",
        db=None,
    )

    status = integrations_service.get_integrations_status().as_dict()
    assert status["providers"]["notion"]["configured"] is True
    assert status["providers"]["github_issues"]["configured"] is True

    _ = integrations_service.disconnect_provider("github_issues", db=None)
    status_after_disconnect = integrations_service.get_integrations_status().as_dict()
    assert status_after_disconnect["providers"]["github_issues"]["configured"] is False
    assert status_after_disconnect["providers"]["notion"]["configured"] is True

    saved_path = runtime_config.config_file_path()
    payload = json.loads(saved_path.read_text(encoding="utf-8"))
    assert payload["providers"]["notion"]["credentials"]["token"] == "notion_token_placeholder"
    assert payload["providers"]["github_issues"]["credentials"] == {}
