"""View and search knowledge base information."""

from pathlib import Path
from typing import Optional

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

console = Console()


@click.group(invoke_without_command=True)
@click.option(
    "--path",
    type=click.Path(exists=True, file_okay=False, path_type=Path),
    default=".",
    help="Project directory (default: current directory)",
)
@click.pass_context
def info(ctx, path: Path):
    """View and search the knowledge base.

    Use subcommands to list or search specific content types.
    """
    ctx.ensure_object(dict)
    ctx.obj["path"] = path.resolve()

    if ctx.invoked_subcommand is None:
        # Show overview when no subcommand given
        _show_overview(ctx.obj["path"])


@info.command(name="list")
@click.argument("section", type=click.Choice(["characters", "items", "scenes", "events", "all"]))
@click.pass_context
def list_items(ctx, section: str):
    """List items in a knowledge base section.

    SECTION can be: characters, items, scenes, events, or all
    """
    from agent_xs.core.content import ContentIndex

    project_root = ctx.obj["path"]
    index = ContentIndex(project_root)
    index.load()

    section_map = {
        "characters": "角色",
        "items": "物品",
        "scenes": "场景",
        "events": "事件",
    }

    if section == "all":
        sections_to_show = list(section_map.values())
    else:
        sections_to_show = [section_map[section]]

    for section_name in sections_to_show:
        items = [item for item in index.items.values() if item.section == section_name]

        if items:
            console.print(f"\n[bold]{section_name}[/] ({len(items)})")

            table = Table(show_header=True, header_style="bold")
            table.add_column("Name")
            table.add_column("Path")

            for item in sorted(items, key=lambda x: x.title):
                table.add_row(item.title, item.path)

            console.print(table)
        else:
            console.print(f"\n[bold]{section_name}[/]: [dim]No items[/]")


@info.command()
@click.argument("query")
@click.option(
    "--section",
    "-s",
    type=click.Choice(["characters", "items", "scenes", "events"]),
    help="Limit search to a specific section",
)
@click.pass_context
def search(ctx, query: str, section: Optional[str]):
    """Search the knowledge base.

    QUERY is the search term to look for across all content.
    """
    from agent_xs.core.content import ContentIndex, make_excerpt, normalize_text

    project_root = ctx.obj["path"]
    index = ContentIndex(project_root)
    index.load()

    section_map = {
        "characters": "角色",
        "items": "物品",
        "scenes": "场景",
        "events": "事件",
    }

    sections = [section_map[section]] if section else []

    results = index.search(
        query=query,
        sections=sections,
        characters=[],
        events=[],
        chapter_min=None,
        chapter_max=None,
    )

    if not results:
        console.print(f"\n[yellow]No results found for '{query}'[/]")
        return

    console.print(f"\n[bold]Search results for '{query}'[/] ({len(results)} found)\n")

    terms = [term for term in normalize_text(query).split(" ") if term]

    for item in results[:20]:  # Limit to first 20 results
        console.print(Panel.fit(
            f"[bold]{item.title}[/]\n"
            f"[dim]{item.section} / {item.path}[/]\n\n"
            f"{make_excerpt(item.body_markdown, terms, 200)}",
            border_style="dim",
        ))

    if len(results) > 20:
        console.print(f"\n[dim]... and {len(results) - 20} more results[/]")


@info.command()
@click.argument("name")
@click.pass_context
def show(ctx, name: str):
    """Show detailed information about a specific item.

    NAME is the title or filename of the item to show.
    """
    from agent_xs.core.content import ContentIndex

    project_root = ctx.obj["path"]
    index = ContentIndex(project_root)
    index.load()

    # Find item by title or filename
    matching_items = []
    name_lower = name.lower()

    for item in index.items.values():
        if (
            item.title.lower() == name_lower
            or item.title.lower().startswith(name_lower)
            or Path(item.path).stem.lower() == name_lower
        ):
            matching_items.append(item)

    if not matching_items:
        console.print(f"\n[yellow]No item found matching '{name}'[/]")
        return

    if len(matching_items) > 1:
        console.print(f"\n[yellow]Multiple items match '{name}':[/]")
        for item in matching_items:
            console.print(f"  - {item.title} ({item.section})")
        return

    item = matching_items[0]

    console.print(Panel.fit(
        f"[bold]{item.title}[/]",
        title=f"{item.section}",
        border_style="blue",
    ))

    # Show metadata
    if item.meta:
        console.print("\n[bold]Metadata[/]")
        for key, value in item.meta.items():
            if isinstance(value, list):
                console.print(f"  {key}: {', '.join(str(v) for v in value)}")
            else:
                console.print(f"  {key}: {value}")

    # Show content
    console.print("\n[bold]Content[/]")
    console.print(Markdown(item.body_markdown))


def _show_overview(project_root: Path):
    """Show overview of knowledge base."""
    from agent_xs.core.content import ContentIndex

    try:
        index = ContentIndex(project_root)
        index.load()
    except Exception as e:
        console.print(f"[red]Error loading content:[/] {e}")
        return

    console.print(Panel.fit(
        "[bold]Knowledge Base Overview[/]",
        border_style="blue",
    ))

    section_names = {
        "角色": "Characters",
        "物品": "Items",
        "场景": "Scenes",
        "事件": "Events",
    }

    for section_zh, section_en in section_names.items():
        items = [item for item in index.items.values() if item.section == section_zh]
        if items:
            console.print(f"\n[bold]{section_zh}[/] ({len(items)})")
            for item in sorted(items, key=lambda x: x.title)[:5]:
                console.print(f"  - {item.title}")
            if len(items) > 5:
                console.print(f"  [dim]... and {len(items) - 5} more[/]")

    console.print("\n[dim]Use 'xs info list <section>' to see all items[/]")
    console.print("[dim]Use 'xs info search <query>' to search[/]")
    console.print("[dim]Use 'xs info show <name>' to view details[/]")
