from __future__ import annotations

import json
import sys
import types
from pathlib import Path

from oasyce.services import scheduler as scheduler_module
from oasyce.services.scanner import AssetScanner
from oasyce.services.scheduler import _scan_with_datavault, get_scheduler


def test_scan_with_datavault_prefers_safe_files(monkeypatch, tmp_path: Path):
    safe_file = tmp_path / "safe.txt"
    safe_file.write_text("safe")
    risky_file = tmp_path / "token.txt"
    risky_file.write_text("secret")

    datavault_pkg = types.ModuleType("datavault")
    datavault_scanner = types.ModuleType("datavault.scanner")

    def fake_scan_directory(path: str, recursive: bool = True, skip_privacy: bool = False):
        return {
            "files": [
                {
                    "path": str(safe_file),
                    "hash": "a" * 64,
                    "privacy_risk": "safe",
                },
                {
                    "path": str(risky_file),
                    "hash": "b" * 64,
                    "privacy_risk": "high",
                },
            ]
        }

    datavault_scanner.scan_directory = fake_scan_directory
    monkeypatch.setitem(sys.modules, "datavault", datavault_pkg)
    monkeypatch.setitem(sys.modules, "datavault.scanner", datavault_scanner)

    results = _scan_with_datavault(str(tmp_path), AssetScanner())

    assert results is not None
    assert len(results) == 1
    assert results[0].file_path == str(safe_file)
    assert results[0].sensitivity == "public"
    assert results[0].confidence == 0.95


def test_get_scheduler_resumes_enabled_config(tmp_path: Path):
    scheduler_module._scheduler_instance = None
    (tmp_path / "agent_config.json").write_text(
        json.dumps(
            {
                "enabled": True,
                "interval_hours": 24,
                "scan_paths": [str(tmp_path)],
                "auto_register": True,
                "auto_trade": False,
                "trade_tags": [],
                "trade_max_spend": 10.0,
            }
        ),
        encoding="utf-8",
    )

    scheduler = get_scheduler(str(tmp_path))
    try:
        assert scheduler.status()["running"] is True
    finally:
        scheduler.stop()
        scheduler_module._scheduler_instance = None
