import typer
from rich import print
from rich.console import Console
from rich.panel import Panel
from rich.markdown import Markdown
from rich.table import Table
from .service import JiraService
import os

app = typer.Typer(
    name="jira",
    help="🎫 Jira Issue Management\n\n"
         "Commands to interact with Jira issues:\n"
         "- View issue descriptions\n"
         "- Add comments\n"
         "- Update issues",
    no_args_is_help=True
)

console = Console()

def show_config_error(error: str):
    """Show a nicely formatted configuration error message"""
    panel = Panel(
        f"[red]{error}[/red]\n\n"
        "[yellow]To configure Jira, you need to set the following environment variables:[/yellow]\n\n"
        "  export JIRA_SERVER_URL='https://your-domain.atlassian.net'\n"
        "  export JIRA_EMAIL='your.email@company.com'\n"
        "  export JIRA_TOKEN='your-api-token'\n\n"
        "[blue]For detailed setup instructions:[/blue]\n"
        "  giji jira config",
        title="[red]⚠️  Configuration Error[/red]",
        border_style="red",
        padding=(1, 2)
    )
    console.print(panel)

def get_jira_service() -> JiraService:
    """Helper function to create a JiraService instance"""
    try:
        return JiraService.from_env()
    except ValueError as e:
        show_config_error(str(e))
        raise typer.Exit(1)

@app.command(name="config", help="⚙️  Configure Jira connection settings")
def configure():
    """Configure Jira connection settings"""
    # Show current configuration
    table = Table(title="Current Jira Configuration")
    table.add_column("Variable", style="cyan")
    table.add_column("Value", style="green")
    table.add_column("Status", style="yellow")
    
    # Check each required variable
    variables = {
        "JIRA_SERVER_URL": "Jira server URL",
        "JIRA_EMAIL": "Your email",
        "JIRA_TOKEN": "API Token"
    }
    
    any_missing = False
    for env_var, description in variables.items():
        value = os.getenv(env_var)
        if value:
            # Mask token for security
            display_value = "***" if env_var == "JIRA_TOKEN" and value else value
            status = "[green]✓ Set[/green]"
        else:
            display_value = "[red]Not set[/red]"
            status = "[red]✗ Missing[/red]"
            any_missing = True
            
        table.add_row(env_var, display_value, status)
    
    console.print(table)
    
    if any_missing:
        console.print("\n[yellow]To configure Jira, add these lines to your shell profile (~/.zshrc, ~/.bashrc, etc.):[/yellow]")
        console.print("\n[blue]# Jira Configuration[/blue]")
        console.print("export JIRA_SERVER_URL='https://your-domain.atlassian.net'")
        console.print("export JIRA_EMAIL='your.email@company.com'")
        console.print("export JIRA_TOKEN='your-api-token'")
        
        console.print("\n[yellow]How to get your Jira Server URL:[/yellow]")
        console.print("1. Log in to your Jira instance in your browser")
        console.print("2. Look at the URL in your browser, it should be something like:")
        console.print("   [blue]https://your-company.atlassian.net[/blue]")
        console.print("3. If you're using Jira Server/Data Center instead of Jira Cloud,")
        console.print("   use your custom domain, e.g., [blue]https://jira.your-company.com[/blue]")
        
        console.print("\n[yellow]Email Address:[/yellow]")
        console.print("• This is the email you use to log in to Jira")
        
        console.print("\n[yellow]How to get your API Token:[/yellow]")
        console.print("1. Go to [link]https://id.atlassian.com/manage-profile/security/api-tokens[/link]")
        console.print("2. Click 'Create API token'")
        console.print("3. Give it a name (e.g., 'giji-cli')")
        console.print("4. Copy the token - it should look like a long string of random characters")
        console.print("5. Make sure to copy the entire token without any extra spaces")
        
    else:
        console.print("\n[green]✨ Jira is properly configured![/green]")

@app.command(name="describe", help="📖 Get the description of a Jira issue")
def get_issue_description(
    issue_key: str = typer.Argument(
        ...,
        help="The Jira issue key (e.g., 'PROJECT-123')",
        show_default=False
    ),
    format: bool = typer.Option(
        False,
        "--format", "-f",
        help="Show raw description with formatting"
    )
):
    """
    Get the description of a Jira issue.
    The description will be formatted as markdown by default.
    """
    try:
        jira = get_jira_service()
        description = jira.get_issue_description(issue_key)
        
        if not description:
            console.print(f"[yellow]⚠️  Issue {issue_key} has no description[/yellow]")
            raise typer.Exit(0)
        
        if format:
            md = Markdown(description)
            console.print(Panel(
                md,
                title=f"[blue]📝 Description for {issue_key}[/blue]",
                expand=False,
                padding=(1, 2)
            ))
        else:
            print(description)
            
    except Exception as e:
        console.print(f"[red]Error:[/red] {str(e)}")
        raise typer.Exit(1)

@app.command(name="comment", help="💬 Add a comment to a Jira issue")
def add_comment(
    issue_key: str = typer.Argument(..., help="The Jira issue key (e.g., 'PROJECT-123')"),
    comment: str = typer.Argument(..., help="The comment text to add")
):
    """Add a comment to a Jira issue"""
    try:
        jira = get_jira_service()
        jira.add_comment(issue_key, comment)
        console.print(f"[green]Successfully added comment to {issue_key}[/green]")
    except Exception as e:
        console.print(f"[red]Error:[/red] {str(e)}")
        raise typer.Exit(1)


if __name__ == "__main__":
    app() 