from __future__ import annotations

import importlib.util
import platform

from flow_xhs.runtime.app_utils import get_system_chrome_path
from flow_xhs.runtime.database.manager import init_db
from flow_xhs.runtime.paths import APP_HOME, LOG_DIR, OUTPUT_DIR, configure_legacy_data_paths, ensure_runtime_dirs



def execute_doctor() -> dict:
    ensure_runtime_dirs()
    configure_legacy_data_paths()
    init_db()
    playwright_installed = importlib.util.find_spec("playwright") is not None
    system_chrome_path = get_system_chrome_path() or ""
    checks = {
        "python": {
            "ok": True,
            "version": platform.python_version(),
        },
        "playwright": {
            "ok": playwright_installed,
            "installed": playwright_installed,
        },
        "system_chrome": {
            "ok": True,
            "found": bool(system_chrome_path),
            "path": system_chrome_path,
            "preferred": True,
        },
        "runtime_dirs": {
            "ok": True,
            "app_home": str(APP_HOME),
            "log_dir": str(LOG_DIR),
            "output_dir": str(OUTPUT_DIR),
        },
        "storage": {
            "ok": True,
            "mode": "file_primary",
            "accounts_dir": str(APP_HOME / "accounts"),
            "settings_file": str(APP_HOME / "settings.json"),
            "task_schedules_file": str(APP_HOME / "task_schedules.json"),
        },
    }
    checks["overall_ok"] = all(item.get("ok", False) for item in checks.values() if isinstance(item, dict))
    return checks
