"""Dobby web dashboard — minimal monitoring UI."""
import os

from aiohttp import web

TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "templates")
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
ASSETS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "assets")
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))


async def dashboard_page(request):
    """Serve the dashboard HTML page with configurable URLs."""
    html_path = os.path.join(TEMPLATE_DIR, "dashboard.html")
    with open(html_path) as f:
        html = f.read()
    hub_url = request.app.get("hub_url", "")
    github_url = request.app.get("github_url", "")
    html = html.replace("{{HUB_URL}}", hub_url)
    html = html.replace("{{GITHUB_URL}}", github_url)
    return web.Response(text=html, content_type="text/html")


async def serve_asset(request):
    """Serve static assets (logo, etc.)."""
    filename = request.match_info["filename"]
    filepath = os.path.join(ASSETS_DIR, filename)
    if not os.path.exists(filepath):
        raise web.HTTPNotFound()
    return web.FileResponse(filepath)


async def serve_static(request):
    """Serve static CSS/JS files for the dashboard."""
    filename = request.match_info["filename"]
    # Prevent directory traversal
    if ".." in filename or "/" in filename:
        raise web.HTTPForbidden()
    filepath = os.path.join(STATIC_DIR, filename)
    if not os.path.exists(filepath):
        raise web.HTTPNotFound()
    resp = web.FileResponse(filepath)
    resp.headers["Cache-Control"] = "no-cache, must-revalidate"
    return resp


async def serve_markdown(request):
    """Serve a markdown file as JSON {content: "..."} for the dashboard to render."""
    name = request.match_info["name"]
    if name not in ("changelog", "wishlist"):
        raise web.HTTPNotFound()
    filename = {"changelog": "CHANGELOG.md", "wishlist": "WISHLIST.md"}[name]
    filepath = os.path.join(REPO_ROOT, filename)
    if not os.path.exists(filepath):
        return web.json_response({"content": f"# {name.title()}\n\nNo {filename} found."})
    with open(filepath, encoding="utf-8") as f:
        content = f.read()
    return web.json_response({"content": content})


def setup_dashboard(app: web.Application):
    """Add dashboard and Slack interaction routes to the aiohttp app."""
    app.router.add_get("/dashboard", dashboard_page)
    app.router.add_get("/assets/{filename}", serve_asset)
    app.router.add_get("/static/{filename}", serve_static)
    app.router.add_get("/docs/{name}", serve_markdown)

    # Slack Block Kit interactions endpoint
    from dobby.core.api import slack_command, slack_interactions
    app.router.add_post("/slack/interactions", slack_interactions)

    # Slack /dobby slash command endpoint
    app.router.add_post("/slack/command", slack_command)
