import os
import subprocess
import shutil
from typing import Dict

class DeployManager:
    BASE_APPS_DIR = "/root/Apps"

    @staticmethod
    def run_command(command: str, cwd: str = None):
        result = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=cwd)
        return {
            "success": result.returncode == 0,
            "output": (result.stdout or result.stderr).strip()
        }

    def magic_deploy(self, git_url: str) -> str:
        if not git_url.endswith(".git"):
            return "Erro: URL do repositório inválida (deve terminar em .git)."

        repo_name = git_url.split("/")[-1].replace(".git", "")
        target_dir = os.path.join(self.BASE_APPS_DIR, repo_name)

        if os.path.exists(target_dir):
            return f"Erro: O diretório {target_dir} já existe. Use /bash git pull se quiser atualizar."

        # 1. Clone
        print(f"[DEPLOY] Clonando {git_url}...")
        clone_res = self.run_command(f"git clone {git_url} {target_dir}")
        if not clone_res["success"]:
            return f"Falha no clone: {clone_res['output']}"

        # 2. Detecção de Stack
        files = os.listdir(target_dir)
        strategy = ""
        
        if "docker-compose.yml" in files or "docker-compose.yaml" in files:
            strategy = "Docker Compose"
            deploy_res = self.run_command("docker compose up -d", cwd=target_dir)
        elif "package.json" in files:
            strategy = "Node.js (PM2)"
            self.run_command("npm install", cwd=target_dir)
            deploy_res = self.run_command(f"pm2 start index.js --name {repo_name}", cwd=target_dir)
        elif "requirements.txt" in files:
            strategy = "Python (PM2/Gunicorn)"
            self.run_command("pip install -r requirements.txt", cwd=target_dir)
            # Tenta encontrar o arquivo principal
            main_file = "main.py" if "main.py" in files else ("app.py" if "app.py" in files else None)
            if main_file:
                deploy_res = self.run_command(f"pm2 start {main_file} --name {repo_name}", cwd=target_dir)
            else:
                return f"Repositório clonado ({strategy}), mas não encontrei main.py ou app.py para iniciar."
        else:
            return f"Repositório clonado em {target_dir}, mas não detectei uma stack automática (Docker, Node ou Python)."

        if deploy_res["success"]:
            return f"✅ **Deploy Mágico Concluído!**\n- **Repo:** {repo_name}\n- **Estratégia:** {strategy}\n- **Status:** Sucesso"
        else:
            return f"❌ **Falha no Deploy ({strategy}):**\n{deploy_res['output']}"

if __name__ == "__main__":
    # Teste rápido
    pass
