from typing import Optional
import sys

class GudbError(Exception):
    """Base exception for all gudb related errors."""
    pass

class ConfigurationError(GudbError):
    """Raised when the SDK is misconfigured."""
    pass

class InterceptionError(GudbError):
    """Raised when there is an issue intercepting a database query."""
    pass

class DisasterBlockedError(GudbError):
    """
    Raised when a query is blocked because it was identified as a 
    production-halting disaster.
    """
    def __init__(
        self, 
        message: str, 
        issue: str, 
        impact: str, 
        fix: Optional[str] = None,
        query: str = "",
        reason: str = "",
        ai_advisory: str = "",
        dashboard_url: str = ""
    ):
        self.issue = issue
        self.impact = impact
        self.fix = fix
        self.query = query
        self.reason = reason
        self.ai_advisory = ai_advisory
        self.dashboard_url = dashboard_url
        
        # Plain text for production logging
        parts = [f"[gudb] ACCESS DENIED"]
        parts.append(f"ISSUE: {issue}")
        parts.append(f"IMPACT: {impact}")
        if fix:
            parts.append(f"FIX: {fix}")
        if ai_advisory:
            parts.append(f"AI_ADVISORY: {ai_advisory}")
        
        plain_message = " | ".join(parts)
        super().__init__(plain_message)
    
    def format_pretty(self) -> str:
        """Format with ANSI colors for CLI output (only if TTY)."""
        if not sys.stdout.isatty():
            return str(self)
        
        # ANSI Colors for terminal output
        RED = "\033[91m"
        YELLOW = "\033[93m"
        CYAN = "\033[96m"
        BLUE = "\033[94m"
        GREEN = "\033[92m"
        BOLD = "\033[1m"
        RESET = "\033[0m"
        
        banner = f"\n{RED}{BOLD}🛑 [gudb] ACCESS DENIED - DATABASE SEATBELT ACTIVATED{RESET}"
        issue_line = f"   {BOLD}ISSUE:{RESET}  {YELLOW}{self.issue}{RESET}"
        impact_line = f"   {BOLD}IMPACT:{RESET} {RED}{self.impact}{RESET}"
        
        lines = [banner, issue_line, impact_line]
        
        if self.fix:
            fix_line = f"   {BOLD}FIX:{RESET}    {GREEN}{self.fix}{RESET}"
            lines.append(fix_line)
        
        # AI Advisory (optional, only in remote/hybrid mode)
        if self.ai_advisory:
            lines.append("")
            lines.append(f"   {BLUE}🤖 AI ADVISORY:{RESET}")
            lines.append(f"   {self.ai_advisory}")
        
        # Dashboard link
        if self.dashboard_url:
            lines.append("")
            lines.append(f"   {CYAN}📺 For more recommendations, visit:{RESET} {self.dashboard_url}")
        
        return "\n".join(lines)

class ProviderError(GudbError):
    """Raised when the AI provider (Remote/Local) fails or times out."""
    pass
