"""Tests for configuration loading and environment overrides."""
import pytest

from ayn_antivirus.config import Config
from ayn_antivirus.constants import DEFAULT_DASHBOARD_HOST, DEFAULT_DASHBOARD_PORT


def test_default_config():
    c = Config()
    assert c.dashboard_port == DEFAULT_DASHBOARD_PORT
    assert c.dashboard_host == DEFAULT_DASHBOARD_HOST
    assert c.auto_quarantine is False
    assert c.enable_yara is True
    assert c.enable_heuristics is True
    assert isinstance(c.scan_paths, list)
    assert isinstance(c.exclude_paths, list)
    assert isinstance(c.api_keys, dict)


def test_config_env_port_host(monkeypatch):
    monkeypatch.setenv("AYN_DASHBOARD_PORT", "9999")
    monkeypatch.setenv("AYN_DASHBOARD_HOST", "127.0.0.1")
    c = Config()
    c._apply_env_overrides()
    assert c.dashboard_port == 9999
    assert c.dashboard_host == "127.0.0.1"


def test_config_env_auto_quarantine(monkeypatch):
    monkeypatch.setenv("AYN_AUTO_QUARANTINE", "true")
    c = Config()
    c._apply_env_overrides()
    assert c.auto_quarantine is True


def test_config_scan_path_env(monkeypatch):
    monkeypatch.setenv("AYN_SCAN_PATH", "/tmp,/var")
    c = Config()
    c._apply_env_overrides()
    assert "/tmp" in c.scan_paths
    assert "/var" in c.scan_paths


def test_config_max_file_size_env(monkeypatch):
    monkeypatch.setenv("AYN_MAX_FILE_SIZE", "12345")
    c = Config()
    c._apply_env_overrides()
    assert c.max_file_size == 12345


def test_config_load_missing_file():
    """Loading from non-existent file returns defaults."""
    c = Config.load("/nonexistent/path/config.yaml")
    assert c.dashboard_port == DEFAULT_DASHBOARD_PORT
    assert isinstance(c.scan_paths, list)


def test_config_load_yaml(tmp_path):
    """Loading a valid YAML config file picks up values."""
    cfg_file = tmp_path / "config.yaml"
    cfg_file.write_text(
        "scan_paths:\n  - /opt\nauto_quarantine: true\ndashboard_port: 8888\n"
    )
    c = Config.load(str(cfg_file))
    assert c.scan_paths == ["/opt"]
    assert c.auto_quarantine is True
    assert c.dashboard_port == 8888


def test_config_env_overrides_yaml(tmp_path, monkeypatch):
    """Environment variables take precedence over YAML."""
    cfg_file = tmp_path / "config.yaml"
    cfg_file.write_text("dashboard_port: 1111\n")
    monkeypatch.setenv("AYN_DASHBOARD_PORT", "2222")
    c = Config.load(str(cfg_file))
    assert c.dashboard_port == 2222


def test_all_fields_accessible():
    """Every expected config attribute exists."""
    c = Config()
    for attr in [
        "scan_paths", "exclude_paths", "quarantine_path", "db_path",
        "log_path", "auto_quarantine", "scan_schedule", "max_file_size",
        "enable_yara", "enable_heuristics", "enable_realtime_monitor",
        "dashboard_host", "dashboard_port", "dashboard_db_path", "api_keys",
    ]:
        assert hasattr(c, attr), f"Missing config attribute: {attr}"
