from __future__ import annotations
import os
import socket
import subprocess
import threading
import time
from pathlib import Path

try:
    import psutil  # type: ignore
except Exception:
    psutil = None

class TaskRunner:
    def run(self, command, cwd=None, shell=True):
        completed = subprocess.run(command, cwd=cwd, shell=shell, capture_output=True, text=True)
        return {
            "returncode": completed.returncode,
            "stdout": completed.stdout,
            "stderr": completed.stderr,
        }

class BackgroundJobManager:
    def __init__(self):
        self.jobs = []

    def start(self, target, *args, **kwargs):
        thread = threading.Thread(target=target, args=args, kwargs=kwargs, daemon=True)
        thread.start()
        self.jobs.append(thread)
        return thread

class ProcessMonitor:
    def list_processes(self):
        if psutil is None:
            return []
        return [{"pid": p.pid, "name": p.name()} for p in psutil.process_iter(attrs=["name"])]

class PortChecker:
    def is_open(self, host="127.0.0.1", port=80, timeout=0.5):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        try:
            return sock.connect_ex((host, int(port))) == 0
        finally:
            sock.close()

class HealthSuite:
    def run_checks(self, checks):
        results = []
        for name, callback in checks:
            try:
                ok = bool(callback())
                results.append({"name": name, "ok": ok})
            except Exception as exc:
                results.append({"name": name, "ok": False, "error": str(exc)})
        return results

class DependencyGraph:
    def __init__(self):
        self.edges = {}

    def add_service(self, name, depends_on=None):
        self.edges[name] = list(depends_on or [])

    def as_dict(self):
        return dict(self.edges)

class Scheduler:
    def __init__(self):
        self.tasks = []

    def every(self, seconds, callback, name="task"):
        self.tasks.append({"name": name, "seconds": seconds, "callback": callback})
        return name

class ServiceController:
    def start(self, command, cwd=None):
        return subprocess.Popen(command, cwd=cwd, shell=True)

    def stop(self, process):
        try:
            process.terminate()
            return True
        except Exception:
            return False

    def restart(self, process, command, cwd=None):
        self.stop(process)
        return self.start(command, cwd=cwd)

class RecentProjects:
    def __init__(self):
        self.items = []

    def add(self, path):
        path = str(path)
        if path in self.items:
            self.items.remove(path)
        self.items.insert(0, path)
        self.items = self.items[:20]

    def list(self):
        return list(self.items)

class WorkspaceProfiles:
    def __init__(self):
        self.profiles = {}

    def save(self, name, data):
        self.profiles[name] = data

    def load(self, name, default=None):
        return self.profiles.get(name, default)
