from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Optional


@dataclass
class DriverDeploymentPlan:
    inf_path: Path
    sys_path: Path
    service_name: str = "ProcessMonitor"
    expected_start_type: str = "SERVICE_DEMAND_START"

    def validate(self) -> dict:
        issues = []

        if not self.inf_path.exists():
            issues.append(f"Missing INF: {self.inf_path}")
        if not self.sys_path.exists():
            issues.append(f"Missing SYS: {self.sys_path}")

        inf_text = self.inf_path.read_text(encoding="utf-8", errors="ignore") if self.inf_path.exists() else ""
        config_ok = "SERVICE_DEMAND_START" in inf_text or "StartType = 3" in inf_text
        if not config_ok:
            issues.append("INF should use demand-start service configuration for lab-safe installation")

        repo_root = self.inf_path.parent.parent
        install_script = repo_root / "scripts" / "install_driver.ps1"
        uninstall_script = repo_root / "scripts" / "uninstall_driver.ps1"

        dry_run = {
            "install_script_exists": install_script.exists(),
            "uninstall_script_exists": uninstall_script.exists(),
            "driver_package_ready": self.inf_path.exists() and self.sys_path.exists() and config_ok,
            "package_files": {
                "inf": self.inf_path.exists(),
                "sys": self.sys_path.exists(),
            },
            "service_mode": "demand_start" if config_ok else "unknown",
        }

        return {
            "service_name": self.service_name,
            "valid": not issues,
            "issues": issues,
            "expected_start_type": self.expected_start_type,
            "dry_run": dry_run,
        }


class DeploymentValidator:
    def __init__(self, repo_root: Optional[str | Path] = None):
        base = Path(repo_root) if repo_root is not None else Path(__file__).resolve().parent.parent
        self.plan = DriverDeploymentPlan(
            inf_path=base / "driver" / "ProcessMonitor.inf",
            sys_path=base / "driver" / "ProcessMonitor.sys",
        )

    def validate(self) -> dict:
        return self.plan.validate()
