from __future__ import annotations
import json
import importlib.util
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
SOURCE = (ROOT / "auto_service8700_manager.py").read_text(encoding="utf-8")


def _config(name: str) -> dict:
    return json.loads((ROOT / name).read_text(encoding="utf-8"))


def test_version_and_retired_service_removed() -> None:
    assert '"version": "2.3.8.228"' in SOURCE
    assert 'direct_schedule_activation' in SOURCE
    assert 'ws_user_mouse_idle_10s' not in SOURCE
    for cfg_name in ["auto_service8700_manager.default.json", "auto_service8700_manager.json"]:
        cfg = _config(cfg_name)
        assert cfg["version"] == "2.3.8.228"
        assert cfg["version_name"] == "2.3.8.228"
        names = {str(x.get("name", "")).upper() for x in cfg.get("services", [])}
        assert "HEART8772" not in names
        ws = next(x for x in cfg["services"] if str(x.get("name", "")).upper() == "WS8771")
        forbidden = {"ws8771_heart_client.py", "ws8771_ig_auto_click_download.py", "ws8771_ig_auto_download.py", "ws8771_origin_crosscheck.py"}
        assert not forbidden.intersection(ws.get("watch_files", []))
        assert "Heart8772" not in (cfg.get("bat_catalog") or {})
        assert "Heart8772" not in (cfg.get("shared_watch") or {}).get("restart_services", [])


def test_analyze8780_is_auto_started_and_health_checked() -> None:
    for cfg_name in ["auto_service8700_manager.default.json", "auto_service8700_manager.json"]:
        cfg = _config(cfg_name)
        service = next(x for x in cfg["services"] if str(x.get("name", "")).upper() == "ANALYZE8780")
        assert service["enabled"] is True
        assert service["start_on_manager_start"] is True
        assert service["ports"] == [8780] and service["health_ports"] == [8780]
        assert service["health_mode"] == "http_json"
        assert service["health_path"] == "/api/health"
        assert service["health_expect_key"] == "ok"
        assert service["health_expect_value"] is True
        assert service["work_dir"] == r"D:\_St\Analyze8780"
        assert "analyze8780_main.py" in service["bat_text"]
        assert "Analyze8780" in cfg["bat_catalog"]
        assert "Analyze8780" in cfg["shared_watch"]["restart_services"]
    for token in [
        'mode in ("http", "http_json", "json")',
        'analyze8780_port_ok',
        'analyze8780_api_ok',
        '8780:{analyze_text}',
    ]:
        assert token in SOURCE


def test_source_does_not_restore_retired_heart_service() -> None:
    for token in ['"name": "Heart8772"', 'D:\\_St\\Heart8772', 'heart8772_position.py', 'ws8771_heart_client.py', 'ws8771_ig_auto_click_download.py']:
        assert token not in SOURCE


def test_http_json_health_mode_runtime(monkeypatch) -> None:
    spec = importlib.util.spec_from_file_location("auto8700_v228_runtime", ROOT / "auto_service8700_manager.py")
    assert spec and spec.loader
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    cfg = module.default_config()
    assert cfg["version"] == "2.3.8.228"
    assert any(str(x.get("name", "")).upper() == "ANALYZE8780" for x in cfg["services"])
    monkeypatch.setattr(module, "http_json_get", lambda url, timeout=1.2: {"ok": True, "service": "Analyze8780"})
    service = {
        "health_ports": [8780],
        "health_mode": "http_json",
        "health_path": "/api/health",
        "health_expect_key": "ok",
        "health_expect_value": True,
    }
    assert module.health_ok(service) is True
    monkeypatch.setattr(module, "http_json_get", lambda url, timeout=1.2: {"ok": False})
    assert module.health_ok(service) is False
