"""Server MCP minimal care ruleaza comenzi PowerShell. Fara dependinte: doar Python 3.

Pe Windows foloseste pwsh.exe daca exista, altfel powershell.exe.
Pe Linux/macOS are nevoie de pwsh (PowerShell 7) instalat; daca lipseste, spune asta
in loc sa esueze tacut.
"""
import json, os, shutil, subprocess, sys

def gaseste_pwsh():
    for c in ("pwsh", "pwsh.exe", "powershell.exe", "powershell"):
        p = shutil.which(c)
        if p:
            return p
    return None

PWSH = gaseste_pwsh()

UNELTE = [{
    "name": "run",
    "description": ("Ruleaza o comanda PowerShell si intoarce iesirea. "
                    "Pe Windows foloseste PowerShell-ul sistemului; pe Linux/macOS cere pwsh."),
    "inputSchema": {
        "type": "object",
        "properties": {
            "comanda": {"type": "string", "description": "comanda PowerShell de rulat"},
            "timeout": {"type": "integer", "description": "secunde, implicit 120"},
        },
        "required": ["comanda"],
    },
}]

def ruleaza(comanda, timeout=120):
    if not PWSH:
        return ("PowerShell nu e instalat pe masina asta.\n"
                "Pe Linux: sudo snap install powershell --classic\n"
                "Pe macOS: brew install --cask powershell")
    try:
        r = subprocess.run([PWSH, "-NoProfile", "-NonInteractive", "-Command", comanda],
                           capture_output=True, text=True, timeout=timeout)
        out = (r.stdout or "") + (("\n[stderr]\n" + r.stderr) if r.stderr.strip() else "")
        if r.returncode != 0:
            out += "\n[cod de iesire: %d]" % r.returncode
        return out.strip() or "(fara iesire)"
    except subprocess.TimeoutExpired:
        return "comanda a depasit %d secunde si a fost oprita" % timeout
    except Exception as e:
        return "eroare: %s" % e

def raspunde(id_, rezultat=None, eroare=None):
    m = {"jsonrpc": "2.0", "id": id_}
    if eroare is not None:
        m["error"] = eroare
    else:
        m["result"] = rezultat
    sys.stdout.write(json.dumps(m) + "\n")
    sys.stdout.flush()

def main():
    for linie in sys.stdin:
        linie = linie.strip()
        if not linie:
            continue
        try:
            cerere = json.loads(linie)
        except Exception:
            continue
        m, id_ = cerere.get("method"), cerere.get("id")
        if m == "initialize":
            raspunde(id_, {"protocolVersion": "2024-11-05",
                           "capabilities": {"tools": {}},
                           "serverInfo": {"name": "powershell", "version": "1.0"}})
        elif m == "tools/list":
            raspunde(id_, {"tools": UNELTE})
        elif m == "tools/call":
            p = cerere.get("params", {})
            a = p.get("arguments", {})
            text = ruleaza(a.get("comanda", ""), int(a.get("timeout", 120)))
            raspunde(id_, {"content": [{"type": "text", "text": text}]})
        elif m and m.startswith("notifications/"):
            pass
        elif id_ is not None:
            raspunde(id_, eroare={"code": -32601, "message": "metoda necunoscuta: %s" % m})

if __name__ == "__main__":
    main()
