"""Tests for config module."""

from pathlib import Path

from appxen_cli.config import Profile, load_profile, save_profile


class TestConfig:

    def test_load_profile_from_env(self, monkeypatch, tmp_path):
        """Env vars override config file."""
        monkeypatch.setenv("APPXEN_API_KEY", "axgw_test_env_key")
        monkeypatch.setenv("APPXEN_ENDPOINT", "http://localhost:8000")

        prof = load_profile()
        assert prof is not None
        assert prof.api_key == "axgw_test_env_key"
        assert prof.endpoint == "http://localhost:8000"

    def test_load_profile_missing_returns_none(self, monkeypatch, tmp_path):
        """Missing config returns None."""
        monkeypatch.delenv("APPXEN_API_KEY", raising=False)
        monkeypatch.delenv("APPXEN_ENDPOINT", raising=False)
        monkeypatch.delenv("APPXEN_PROFILE", raising=False)
        import appxen_cli.config as cfg
        monkeypatch.setattr(cfg, "CONFIG_FILE", tmp_path / "nonexistent.toml")

        prof = load_profile()
        assert prof is None

    def test_save_and_load_profile(self, monkeypatch, tmp_path):
        """Save then load roundtrips correctly."""
        monkeypatch.delenv("APPXEN_API_KEY", raising=False)
        monkeypatch.delenv("APPXEN_ENDPOINT", raising=False)
        monkeypatch.delenv("APPXEN_PROFILE", raising=False)

        import appxen_cli.config as cfg
        config_dir = tmp_path / "config"
        config_file = config_dir / "config.toml"
        monkeypatch.setattr(cfg, "CONFIG_DIR", config_dir)
        monkeypatch.setattr(cfg, "CONFIG_FILE", config_file)

        save_profile(api_key="axgw_test_123", endpoint="https://api.test.com")
        prof = load_profile()
        assert prof is not None
        assert prof.api_key == "axgw_test_123"
        assert prof.endpoint == "https://api.test.com"

        # Check file permissions
        assert oct(config_file.stat().st_mode)[-3:] == "600"

    def test_multiple_profiles(self, monkeypatch, tmp_path):
        """Multiple profiles can coexist."""
        monkeypatch.delenv("APPXEN_API_KEY", raising=False)
        monkeypatch.delenv("APPXEN_ENDPOINT", raising=False)
        monkeypatch.delenv("APPXEN_PROFILE", raising=False)

        import appxen_cli.config as cfg
        config_dir = tmp_path / "config"
        config_file = config_dir / "config.toml"
        monkeypatch.setattr(cfg, "CONFIG_DIR", config_dir)
        monkeypatch.setattr(cfg, "CONFIG_FILE", config_file)

        save_profile(api_key="axgw_prod", profile="default")
        save_profile(api_key="axgw_staging", endpoint="http://localhost:8000", profile="staging")

        prod = load_profile("default")
        staging = load_profile("staging")

        assert prod is not None
        assert prod.api_key == "axgw_prod"
        assert staging is not None
        assert staging.api_key == "axgw_staging"
        assert staging.endpoint == "http://localhost:8000"

    def test_env_key_only_defaults_endpoint(self, monkeypatch):
        """When only APPXEN_API_KEY is set, endpoint uses default."""
        monkeypatch.setenv("APPXEN_API_KEY", "axgw_test")
        monkeypatch.delenv("APPXEN_ENDPOINT", raising=False)

        prof = load_profile()
        assert prof is not None
        from appxen_cli.config import DEFAULT_ENDPOINT
        assert prof.endpoint == DEFAULT_ENDPOINT

    def test_profile_ignores_legacy_orchestrator_fields(self, monkeypatch, tmp_path):
        """Loading a config file with old orchestrator_url/tenant_id fields works."""
        monkeypatch.delenv("APPXEN_API_KEY", raising=False)
        monkeypatch.delenv("APPXEN_ENDPOINT", raising=False)
        monkeypatch.delenv("APPXEN_PROFILE", raising=False)

        import appxen_cli.config as cfg
        config_dir = tmp_path / "config"
        config_file = config_dir / "config.toml"
        monkeypatch.setattr(cfg, "CONFIG_DIR", config_dir)
        monkeypatch.setattr(cfg, "CONFIG_FILE", config_file)

        # Write a config file with legacy fields
        import tomli_w
        config_dir.mkdir(parents=True, exist_ok=True)
        data = {
            "default": {
                "api_key": "axgw_legacy",
                "endpoint": "https://api.test.com",
                "orchestrator_url": "https://old-orch.test.com",
                "tenant_id": "old-tenant",
            }
        }
        with open(config_file, "wb") as f:
            tomli_w.dump(data, f)

        prof = load_profile()
        assert prof is not None
        assert prof.api_key == "axgw_legacy"
        assert prof.endpoint == "https://api.test.com"
        # Legacy fields are silently ignored (no orchestrator_url attr)
        assert not hasattr(prof, "orchestrator_url")
        assert not hasattr(prof, "tenant_id")
