import os
import sys
import json
from pathlib import Path
import pytest
import unittest
from unittest.mock import MagicMock

ROOT = Path(__file__).resolve().parents[1]
SRC = ROOT / "src"
if str(SRC) not in sys.path:
    sys.path.insert(0, str(SRC))
os.environ.setdefault("ARMORER_SANDBOX", "0")

from armorer.config import ConfigManager
from armorer.registry import AppRegistry

@pytest.fixture(autouse=True)
def isolate_armorer_state(tmp_path, monkeypatch):
    armorer_home = tmp_path / ".armorer"
    armorer_home.mkdir(parents=True, exist_ok=True)
    monkeypatch.setenv("HOME", str(tmp_path))
    monkeypatch.setenv("OPENAI_API_KEY", os.environ.get("OPENAI_API_KEY") or "sk-test-openai")
    monkeypatch.setattr(AppRegistry, "REGISTRY_FILE", armorer_home / "registry.json")
    monkeypatch.setattr(ConfigManager, "VAULT_FILE", armorer_home / "vault.json")
    monkeypatch.setattr(ConfigManager, "CONFIG_DIR", armorer_home)
    (armorer_home / "vault.json").write_text(
        json.dumps({"keys": {}, "secrets": {"OPENAI_API_KEY": "sk-test-openai"}}, indent=2)
    )

@pytest.fixture(autouse=True)
def mock_agent_backend(monkeypatch):
    """Mocks the OpenAI Agents Agent class for tests that construct BaseAgent."""
    mock_agent_instance = MagicMock()

    try:
        import agents
        monkeypatch.setattr("agents.Agent", MagicMock(return_value=mock_agent_instance))
    except ImportError:
        pass

    return mock_agent_instance

@pytest.fixture
def mock_config_manager():
    """Mocks ConfigManager to prevent keyring/env access during tests."""
    with unittest.mock.patch("armorer.config.ConfigManager") as MockConfig:
        yield MockConfig
