"""Show project status and progress."""

from pathlib import Path

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

console = Console()


@click.command()
@click.option(
    "--path",
    type=click.Path(exists=True, file_okay=False, path_type=Path),
    default=".",
    help="Project directory (default: current directory)",
)
def status(path: Path):
    """Show the current status of the novel project.

    Displays chapter counts, word counts, and prerequisite status.
    """
    from agent_xs.core.pipeline import NovelPipeline
    from agent_xs.core.content import ContentIndex

    project_root = path.resolve()
    pipeline = NovelPipeline(project_root)

    if not pipeline.is_novel_project():
        console.print(
            f"[yellow]Warning:[/] '{project_root}' does not appear to be a novel project.\n"
            "Run [cyan]xs init <name>[/] to create a new project."
        )
        return

    console.print(Panel.fit(
        f"[bold]{project_root.name}[/]",
        title="Project Status",
        border_style="blue",
    ))

    # Prerequisites check
    console.print("\n[bold]Prerequisites[/]")
    is_complete, message = pipeline.check_prerequisites()
    if is_complete:
        console.print(f"  [green]{message}[/]")
    else:
        for line in message.split("\n"):
            if line.strip():
                console.print(f"  [yellow]{line}[/]")

    # Chapter counts
    draft_count, final_count = pipeline.count_chapters()
    console.print("\n[bold]Chapters[/]")
    console.print(f"  Drafts: {draft_count}")
    console.print(f"  Finals: {final_count}")

    # Next action
    if is_complete:
        action, chapter_num = pipeline.get_next_action()
        action_name = "Draft" if action == "draft" else "Finalize"
        console.print(f"\n[bold]Next Action[/]")
        console.print(f"  {action_name} chapter {chapter_num}")

    # Content statistics
    try:
        index = ContentIndex(project_root)
        index.load()

        if index.items:
            console.print("\n[bold]Content Statistics[/]")

            table = Table(show_header=True, header_style="bold")
            table.add_column("Section")
            table.add_column("Count", justify="right")
            table.add_column("Words", justify="right")

            totals = index.totals()
            for section in ["正文", "草稿", "角色", "事件", "物品", "场景"]:
                count = totals["sections"].get(section, 0)
                words = totals["words"].get(section, 0)
                if count > 0:
                    table.add_row(
                        section,
                        str(count),
                        str(words) if words else "-",
                    )

            console.print(table)

            # Character and event summary
            filters = index.filters()
            if filters["characters"]:
                console.print(f"\n[bold]Characters[/]: {', '.join(filters['characters'][:10])}")
                if len(filters["characters"]) > 10:
                    console.print(f"  ... and {len(filters['characters']) - 10} more")

            if filters["events"]:
                console.print(f"\n[bold]Events[/]: {', '.join(filters['events'][:10])}")
                if len(filters["events"]) > 10:
                    console.print(f"  ... and {len(filters['events']) - 10} more")

    except Exception as e:
        console.print(f"\n[dim]Could not load content index: {e}[/]")
