from __future__ import annotations

import json
import types
from dataclasses import dataclass
from pathlib import Path
from typing import List

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


def test_scan_with_sdk_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")

    @dataclass
    class FakeFileInfo:
        path: str
        name: str
        sha256: str
        size: int
        category: str
        tags: list
        privacy_risk: str

    def fake_sdk_scan(paths=None, check_privacy=True, **kw):
        return [
            FakeFileInfo(
                path=str(safe_file), name="safe.txt",
                sha256="a" * 64, size=4, category="document",
                tags=["document"], privacy_risk="safe",
            ),
            FakeFileInfo(
                path=str(risky_file), name="token.txt",
                sha256="b" * 64, size=6, category="document",
                tags=["document"], privacy_risk="high",
            ),
        ]

    sdk_agent_scanner = types.ModuleType("oasyce_sdk.agent.scanner")
    sdk_agent_scanner.scan = fake_sdk_scan
    monkeypatch.setitem(__import__("sys").modules, "oasyce_sdk.agent.scanner", sdk_agent_scanner)

    results = _scan_with_sdk(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
