import subprocess
import requests

class AutoDeployer:
    """Handles automated deployments."""

    def execute_terraform(self, tf_dir: str) -> bool:
        """Executes actual terraform init and apply."""
        try:
            init = subprocess.run(["terraform", "init"], cwd=tf_dir, capture_output=True, text=True, check=False)
            if init.returncode != 0:
                print(f"[AutoDeployer] Init failed: {init.stderr}")
                return False
                
            apply = subprocess.run(["terraform", "apply", "-auto-approve"], cwd=tf_dir, capture_output=True, text=True, check=False)
            if apply.returncode != 0:
                print(f"[AutoDeployer] Apply failed: {apply.stderr}")
                return False
            return True
        except FileNotFoundError:
            print("[AutoDeployer] Error: 'terraform' executable not found.")
            return False
        except Exception as e:
            print(f"[AutoDeployer] Error: {e}")
            return False

    def check_uptime(self, url: str) -> bool:
        """Sends a real GET request to verify the URL is responding."""
        if not url.startswith("http"):
            url = "http://" + url
        try:
            resp = requests.get(url, timeout=5)
            return resp.status_code < 400
        except requests.exceptions.RequestException:
            return False
