"""CLI commands for Jira integration (Phase 5).

Commands:
  antiqa jira show <key>         — Display a Jira ticket summary
  antiqa jira test-cases <key>   — Download & parse test cases from a ticket
  antiqa jira parse-ticket <key> — AI-analyse a ticket for QA context
"""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

console = Console()


def _load_agent():
    from antiqa.config.manager import load_config
    from antiqa.jira.agent import JiraAgent

    config = load_config()
    return JiraAgent(config), config


def run_jira_show(key: str) -> None:
    """Fetch and display a Jira ticket."""
    with console.status(f"[cyan]Fetching {key} from Jira..."):
        agent, _ = _load_agent()
        issue = agent.get_issue(key)

    if "error" in issue:
        console.print(f"[red]Error:[/red] {issue['error']}")
        raise typer.Exit(1)

    panel = Panel(
        f"[bold]{issue.get('summary', 'N/A')}[/bold]\n\n"
        f"[dim]Type:[/dim] {issue.get('issuetype', 'N/A')}  |  "
        f"[dim]Reporter:[/dim] {issue.get('reporter', 'N/A')}\n\n"
        f"{issue.get('description', '')[:500] or '[dim]No description[/dim]'}",
        title=f"[cyan]{key}[/cyan]",
        border_style="green",
    )
    console.print(panel)

    # Show attachments
    with console.status("Checking attachments..."):
        attachments = agent.get_attachments(key)

    if attachments:
        table = Table(title="Attachments", show_lines=True)
        table.add_column("Filename", style="cyan")
        table.add_column("Size", justify="right")
        table.add_column("Type")
        for att in attachments:
            table.add_row(att["filename"], att["size"], att["mime_type"])
        console.print(table)
    else:
        console.print("[dim]No attachments found.[/dim]")


def run_jira_test_cases(key: str, download_dir: str | None = None) -> None:
    """Download test case attachments and parse them."""
    agent, _ = _load_agent()

    from antiqa.jira.attachments import AttachmentDownloader
    from antiqa.jira.test_case_parser import TestCaseFileParser

    dl = AttachmentDownloader(agent, download_dir=download_dir)

    with console.status(f"[cyan]Downloading test cases from {key}..."):
        files = dl.download_all(key)

    if not files:
        console.print(f"[yellow]No test case files (Excel/CSV) found on {key}.[/yellow]")
        raise typer.Exit(0)

    console.print(f"\n[green]Downloaded {len(files)} file(s):[/green]")
    for f in files:
        console.print(f"  • {f.name}")

    parser = TestCaseFileParser()
    cases = parser.parse_many(files)

    if not cases:
        console.print("[yellow]No test cases found in the downloaded files.[/yellow]")
        raise typer.Exit(0)

    console.print(f"\n[bold green]Parsed {len(cases)} test case(s):[/bold green]\n")

    for tc in cases:
        table = Table(
            title=f"[cyan]{tc.id}[/cyan] — {tc.title}",
            show_lines=True,
            title_style="bold",
        )
        table.add_column("#", width=4, justify="right")
        table.add_column("Action")
        table.add_column("Expected Result")
        table.add_column("Test Data", style="dim")

        for step in tc.steps:
            table.add_row(
                str(step.step_number),
                step.action,
                step.expected_result,
                step.test_data or "",
            )
        console.print(table)
        if tc.preconditions:
            console.print(f"  [dim]Precondition:[/dim] {tc.preconditions}")
        if tc.priority:
            console.print(f"  [dim]Priority:[/dim] {tc.priority}")
        console.print()


def run_jira_parse_ticket(key: str) -> None:
    """AI-analyse a ticket for QA context."""
    agent, config = _load_agent()

    from antiqa.jira.ticket_parser import TicketParser

    with console.status(f"[cyan]Fetching {key}..."):
        issue = agent.get_issue(key)

    if "error" in issue:
        console.print(f"[red]Error:[/red] {issue['error']}")
        raise typer.Exit(1)

    parser = TicketParser(config)

    with console.status("[cyan]Analysing ticket with AI..."):
        parsed = parser.parse(issue)

    panel_text = f"[bold]{parsed.summary}[/bold]\n\n"

    if parsed.affected_areas:
        panel_text += "[dim]Affected Areas:[/dim]\n"
        for area in parsed.affected_areas:
            panel_text += f"  • {area}\n"
        panel_text += "\n"

    if parsed.acceptance_criteria:
        panel_text += "[dim]Acceptance Criteria:[/dim]\n"
        for ac in parsed.acceptance_criteria:
            panel_text += f"  • {ac}\n"
        panel_text += "\n"

    if parsed.suggested_scenarios:
        panel_text += "[dim]Suggested Test Scenarios:[/dim]\n"
        for sc in parsed.suggested_scenarios:
            panel_text += f"  • {sc}\n"
        panel_text += "\n"

    if parsed.test_urls:
        panel_text += "[dim]URLs to Test:[/dim]\n"
        for url in parsed.test_urls:
            panel_text += f"  • {url}\n"

    console.print(Panel(
        panel_text,
        title=f"[cyan]{parsed.key}[/cyan] — QA Analysis (priority: {parsed.priority})",
        border_style="green",
    ))


def run_parse_local(file_paths: list[str]) -> None:
    """Parse local Excel/CSV files without Jira (for testing)."""
    from antiqa.jira.test_case_parser import TestCaseFileParser

    parser = TestCaseFileParser()
    paths = [Path(f) for f in file_paths]

    for p in paths:
        if not p.exists():
            console.print(f"[red]File not found: {p}[/red]")
            continue

    cases = parser.parse_many(paths)

    if not cases:
        console.print("[yellow]No test cases found in the provided files.[/yellow]")
        raise typer.Exit(0)

    console.print(f"\n[bold green]Parsed {len(cases)} test case(s):[/bold green]\n")

    for tc in cases:
        table = Table(
            title=f"[cyan]{tc.id}[/cyan] — {tc.title}",
            show_lines=True,
            title_style="bold",
        )
        table.add_column("#", width=4, justify="right")
        table.add_column("Action")
        table.add_column("Expected Result")
        table.add_column("Test Data", style="dim")

        for step in tc.steps:
            table.add_row(
                str(step.step_number),
                step.action,
                step.expected_result,
                step.test_data or "",
            )
        console.print(table)
        if tc.preconditions:
            console.print(f"  [dim]Precondition:[/dim] {tc.preconditions}")
        if tc.priority:
            console.print(f"  [dim]Priority:[/dim] {tc.priority}")
        console.print()
