"""AntiQA CLI entry point."""

from __future__ import annotations

import typer
from rich.console import Console

from antiqa import __version__

app = typer.Typer(
    name="antiqa",
    help="AI-powered QA automation — test your app from Jira tickets.",
    no_args_is_help=True,
)
console = Console()


@app.command()
def run(
    ticket: str = typer.Argument(help="Jira issue key (e.g. PROJ-123) to test."),
    dry_run: bool = typer.Option(False, "--dry-run", help="Show the test plan without executing."),
    record: bool = typer.Option(False, "--record", help="Record a video of the browser session."),
    headed: bool = typer.Option(False, "--headed", help="Force visible (headed) browser."),
    headless: bool = typer.Option(False, "--headless", help="Force headless browser."),
    skip_jira: bool = typer.Option(False, "--skip-jira", help="Skip Jira updates (no comments/bugs)."),
) -> None:
    """Run the full test pipeline for a Jira ticket."""
    from antiqa.cli.run_cmd import run_pipeline

    headed_flag = True if headed else (False if headless else None)
    run_pipeline(ticket, dry_run=dry_run, record=record, headed=headed_flag, skip_jira_updates=skip_jira)


@app.command("run-local")
def run_local(
    files: list[str] = typer.Argument(help="Paths to Excel/CSV test case files."),
    record: bool = typer.Option(False, "--record", help="Record a video of the browser session."),
    headed: bool = typer.Option(False, "--headed", help="Force visible (headed) browser."),
) -> None:
    """Run tests from local Excel/CSV files (no Jira needed)."""
    from antiqa.cli.run_cmd import run_local_pipeline

    run_local_pipeline(files, record=record, headed=True if headed else None)


@app.command()
def init() -> None:
    """Initialize AntiQA in the current directory."""
    from antiqa.cli.init_cmd import run_init

    run_init()


config_app = typer.Typer(help="View and manage project configuration.")
app.add_typer(config_app, name="config")


@config_app.command("show")
def config_show() -> None:
    """Display the current configuration."""
    from antiqa.cli.config_cmd import run_config_show

    run_config_show()


@app.command()
def crawl(
    max_pages: int = typer.Option(50, help="Maximum number of pages to crawl."),
    max_depth: int = typer.Option(5, help="Maximum link depth from the start URL."),
    start_path: str = typer.Option("/", help="Path to start crawling from (e.g. /dashboard)."),
) -> None:
    """Crawl the application and build a navigation graph."""
    from antiqa.cli.crawl_cmd import run_crawl

    run_crawl(max_pages=max_pages, max_depth=max_depth, start_path=start_path)


graph_app = typer.Typer(help="View and manage the navigation graph.")
app.add_typer(graph_app, name="graph")


@graph_app.command("show")
def graph_show() -> None:
    """Display the navigation graph."""
    from antiqa.cli.crawl_cmd import run_graph_show

    run_graph_show()


@app.command("run-flow")
def run_flow(
    name: str = typer.Argument(help="Name of the flow to execute (without .yaml extension)."),
    headed: bool = typer.Option(False, "--headed", help="Force headed (visible) browser."),
) -> None:
    """Execute a named test flow."""
    from antiqa.cli.flow_cmd import run_flow as _run_flow

    _run_flow(name=name, headed=headed or None)


flows_app = typer.Typer(help="List and manage test flows.")
app.add_typer(flows_app, name="flows")


@flows_app.command("list")
def flows_list() -> None:
    """List all available flows."""
    from antiqa.cli.flow_cmd import run_flows_list

    run_flows_list()


@app.command("generate-flows")
def generate_flows(
    overwrite: bool = typer.Option(False, "--overwrite", help="Overwrite existing auto-generated flows."),
    ai: bool = typer.Option(False, "--ai", help="Use AI to generate comprehensive flows with edge cases."),
) -> None:
    """Auto-generate YAML flows from the navigation graph."""
    from antiqa.cli.flow_cmd import run_generate_flows

    run_generate_flows(overwrite=overwrite, ai=ai)


# ── Jira commands ──────────────────────────────────────
jira_app = typer.Typer(help="Jira integration — view tickets, parse test cases, file bugs.")
app.add_typer(jira_app, name="jira")


@jira_app.command("show")
def jira_show(
    key: str = typer.Argument(help="Jira issue key (e.g. PROJ-123)."),
) -> None:
    """Display a Jira ticket summary and attachments."""
    from antiqa.cli.jira_cmd import run_jira_show

    run_jira_show(key)


@jira_app.command("test-cases")
def jira_test_cases(
    key: str = typer.Argument(help="Jira issue key to fetch test cases from."),
    download_dir: str = typer.Option(None, "--dir", help="Directory to save downloaded files."),
) -> None:
    """Download & parse test case attachments from a ticket."""
    from antiqa.cli.jira_cmd import run_jira_test_cases

    run_jira_test_cases(key, download_dir=download_dir)


@jira_app.command("parse-ticket")
def jira_parse_ticket(
    key: str = typer.Argument(help="Jira issue key to analyse."),
) -> None:
    """AI-analyse a ticket for QA context (affected areas, acceptance criteria)."""
    from antiqa.cli.jira_cmd import run_jira_parse_ticket

    run_jira_parse_ticket(key)


@app.command("parse-testcases")
def parse_testcases(
    files: list[str] = typer.Argument(help="Paths to Excel/CSV test case files."),
) -> None:
    """Parse local test case files (no Jira needed — for testing)."""
    from antiqa.cli.jira_cmd import run_parse_local

    run_parse_local(files)


@app.command()
def test(
    description: str = typer.Argument(help="Natural language test description (e.g. 'login with wrong password')."),
    headed: bool = typer.Option(False, "--headed", help="Force visible (headed) browser."),
    save: bool = typer.Option(False, "--save", help="Save the generated flow as a YAML file."),
) -> None:
    """Run a test from a plain English description (AI-powered)."""
    from antiqa.cli.test_cmd import run_natural_test

    run_natural_test(description, headed=headed or None, save=save)


@app.command()
def chat() -> None:
    """Interactive AI-powered QA chat session."""
    from antiqa.cli.chat_cmd import run_chat

    run_chat()


@app.command()
def audit(
    headed: bool = typer.Option(False, "--headed", help="Force visible (headed) browser."),
    max_pages: int = typer.Option(10, help="Maximum pages to audit."),
) -> None:
    """Run an AI accessibility audit on the application."""
    from antiqa.cli.audit_cmd import run_accessibility_audit

    run_accessibility_audit(headed=headed or None, max_pages=max_pages)


@app.command()
def version() -> None:
    """Show the AntiQA version."""
    console.print(f"antiqa [bold cyan]{__version__}[/bold cyan]")


def _version_callback(value: bool) -> None:
    if value:
        console.print(f"antiqa [bold cyan]{__version__}[/bold cyan]")
        raise typer.Exit()


@app.callback()
def main(
    _version: bool = typer.Option(
        False,
        "--version",
        "-v",
        help="Show version and exit.",
        callback=_version_callback,
        is_eager=True,
    ),
) -> None:
    """AntiQA — AI-powered QA automation CLI."""
