"""Tests for config loader (get_config_path and _migrate_config)"""

import os
from pathlib import Path

from nanobot.config.loader import get_config_path, _migrate_config


def test_get_config_path_default():
    """get_config_path returns ~/.nanobot/config.json by default"""
    # Ensure NANOBOT_CONFIG is not set
    env_backup = os.environ.pop("NANOBOT_CONFIG", None)
    try:
        path = get_config_path()
        assert path == Path.home() / ".nanobot" / "config.json"
    finally:
        if env_backup:
            os.environ["NANOBOT_CONFIG"] = env_backup


def test_get_config_path_with_env_var():
    """get_config_path uses NANOBOT_CONFIG env var when set"""
    custom_path = "/tmp/test-nanobot-config.json"
    env_backup = os.environ.get("NANOBOT_CONFIG")
    try:
        os.environ["NANOBOT_CONFIG"] = custom_path
        path = get_config_path()
        assert path == Path(custom_path)
    finally:
        if env_backup:
            os.environ["NANOBOT_CONFIG"] = env_backup
        else:
            os.environ.pop("NANOBOT_CONFIG", None)


def test_migrate_config_with_oauth_credentials():
    """_migrate_config extracts api_key from oauthCredentials"""
    data = {
        "providers": {
            "anthropic": {
                "oauthCredentials": {
                    "access_token": "sk-ant-test-token",
                    "refresh_token": "",
                    "expires_at": 0,
                }
            }
        }
    }

    result = _migrate_config(data)

    # api_key should be extracted
    assert result["providers"]["anthropic"]["api_key"] == "sk-ant-test-token"
    # oauthCredentials should be removed after migration
    assert "oauthCredentials" not in result["providers"]["anthropic"]


def test_migrate_config_without_oauth_credentials():
    """_migrate_config leaves config unchanged when no oauthCredentials"""
    data = {
        "providers": {
            "anthropic": {
                "api_key": "sk-ant-existing-key"
            }
        }
    }

    result = _migrate_config(data)

    # Should remain unchanged
    assert result["providers"]["anthropic"]["api_key"] == "sk-ant-existing-key"
    assert "oauthCredentials" not in result["providers"]["anthropic"]


def test_migrate_config_already_migrated():
    """_migrate_config doesn't overwrite existing api_key"""
    data = {
        "providers": {
            "anthropic": {
                "api_key": "sk-ant-existing-key",
                "oauthCredentials": {
                    "access_token": "sk-ant-oauth-token",
                    "refresh_token": "",
                    "expires_at": 0,
                }
            }
        }
    }

    result = _migrate_config(data)

    # Existing api_key should be preserved
    assert result["providers"]["anthropic"]["api_key"] == "sk-ant-existing-key"
    # oauthCredentials should NOT be removed (api_key already existed)
    assert "oauthCredentials" in result["providers"]["anthropic"]


def test_migrate_config_empty_access_token():
    """_migrate_config skips empty access_token"""
    data = {
        "providers": {
            "anthropic": {
                "oauthCredentials": {
                    "access_token": "",
                    "refresh_token": "",
                    "expires_at": 0,
                }
            }
        }
    }

    result = _migrate_config(data)

    # api_key should not be set
    assert "api_key" not in result["providers"]["anthropic"]
    # oauthCredentials should remain (no migration happened)
    assert "oauthCredentials" in result["providers"]["anthropic"]


def test_migrate_config_preserves_other_fields():
    """_migrate_config preserves other provider config fields"""
    data = {
        "providers": {
            "anthropic": {
                "oauthCredentials": {
                    "access_token": "sk-ant-test-token",
                    "refresh_token": "refresh-token",
                },
                "customField": "customValue",
                "anotherField": 123,
            }
        }
    }

    result = _migrate_config(data)

    # api_key added, oauthCredentials removed
    assert result["providers"]["anthropic"]["api_key"] == "sk-ant-test-token"
    assert "oauthCredentials" not in result["providers"]["anthropic"]
    # Other fields preserved
    assert result["providers"]["anthropic"]["customField"] == "customValue"
    assert result["providers"]["anthropic"]["anotherField"] == 123
