"""YakPanel - Install tasks (one-click install via apt)"""
import subprocess
from app.tasks.celery_app import celery_app

# Map panel package IDs to apt package names (same as soft.py)
PKG_MAP = {
    "nginx": "nginx",
    "mysql-server": "mysql-server",
    "mariadb-server": "mariadb-server",
    "php": "php",
    "php-fpm": "php-fpm",
    "redis-server": "redis-server",
    "postgresql": "postgresql",
    "mongodb": "mongodb",
    "certbot": "certbot",
    "docker": "docker.io",
    "nodejs": "nodejs",
    "npm": "npm",
    "git": "git",
    "python3": "python3",
}


@celery_app.task
def install_software(name: str, version: str = ""):
    """Install software via apt (Debian/Ubuntu). name = package id from soft list."""
    pkg = PKG_MAP.get(name, name)
    try:
        result = subprocess.run(
            f"apt-get update && apt-get install -y {pkg}",
            shell=True,
            capture_output=True,
            timeout=300,
        )
        if result.returncode != 0:
            err = (result.stderr or result.stdout or b"").decode("utf-8", errors="replace")
            return {"status": "failed", "name": name, "error": err.strip()[:500]}
        return {"status": "ok", "name": name, "version": version}
    except subprocess.TimeoutExpired:
        return {"status": "failed", "name": name, "error": "Installation timed out"}
    except Exception as e:
        return {"status": "failed", "name": name, "error": str(e)}
