"""Serve the novel content viewer web application."""

from pathlib import Path

import click
from rich.console import Console

console = Console()


@click.command()
@click.option(
    "--host",
    "-h",
    default="0.0.0.0",
    help="Host to bind to (default: 0.0.0.0)",
)
@click.option(
    "--port",
    "-p",
    default=8000,
    type=int,
    help="Port to bind to (default: 8000)",
)
@click.option(
    "--debug",
    "-d",
    is_flag=True,
    help="Enable debug mode",
)
@click.option(
    "--path",
    type=click.Path(exists=True, file_okay=False, path_type=Path),
    default=".",
    help="Project directory (default: current directory)",
)
def serve(host: str, port: int, debug: bool, path: Path):
    """Start the web server to view novel content.

    Opens a browser-based viewer for exploring chapters,
    characters, events, and other content in your novel project.
    """
    from agent_xs.web import create_app
    from agent_xs.core.pipeline import NovelPipeline

    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."
        )

    console.print(f"\n[bold blue]Starting content viewer[/]")
    console.print(f"  Project: {project_root.name}")
    console.print(f"  URL: [cyan]http://{host}:{port}[/]\n")

    app = create_app(project_root)
    app.run(host=host, port=port, debug=debug)
