"""Flask web application for novel content viewer."""

from pathlib import Path

from flask import Flask, jsonify, render_template, request

from agent_xs.core.content import (
    ContentIndex,
    SECTION_ORDER,
    make_excerpt,
    normalize_text,
    parse_list_param,
    safe_int,
)


def create_app(root: Path) -> Flask:
    """Create Flask application for the given project root."""
    app = Flask(
        __name__,
        static_folder=str(Path(__file__).parent / "static"),
        template_folder=str(Path(__file__).parent / "templates"),
    )

    index = ContentIndex(root)
    index.load()

    @app.get("/")
    def index_page():
        return render_template("index.html", project_name=root.name)

    @app.get("/api/index")
    def api_index():
        items = [item.summary() for item in index.list_items()]
        return jsonify({
            "items": items,
            "filters": index.filters(),
            "totals": index.totals(),
            "sections": list(SECTION_ORDER.keys()),
        })

    @app.get("/api/items")
    def api_items():
        query = request.args.get("q", "")
        sections = parse_list_param(request.args.getlist("section"))
        characters = parse_list_param(request.args.getlist("characters"))
        events = parse_list_param(request.args.getlist("events"))
        chapter_min = safe_int(request.args.get("chapter_min"))
        chapter_max = safe_int(request.args.get("chapter_max"))

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

        terms = [term for term in normalize_text(query).split(" ") if term]
        items = []
        for item in results:
            payload = item.summary()
            payload["excerpt"] = make_excerpt(item.body_markdown, terms)
            items.append(payload)

        return jsonify({
            "items": items,
            "count": len(items),
        })

    @app.get("/api/item/<item_id>")
    def api_item(item_id: str):
        item = index.find_item(item_id)
        if not item:
            return jsonify({"error": "not found"}), 404
        return jsonify(item.detail())

    @app.post("/api/refresh")
    def api_refresh():
        index.load()
        return jsonify({
            "ok": True,
            "count": len(index.items),
        })

    return app
