"""IETF Draft Analyzer — Web Dashboard.

Run with: python src/webui/app.py
"""

from __future__ import annotations

import logging
import os
import sys
import time
from pathlib import Path

# Ensure project src is on path
_project_root = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(_project_root / "src"))

from flask import Flask, g, render_template, request

from webui.auth import init_auth
from webui.analytics import init_analytics
from webui.blueprints import register_blueprints
from webui.data import get_db


# --- App factory ---

def create_app(dev: bool = False) -> Flask:
    """Create and configure the Flask application."""
    application = Flask(
        __name__,
        template_folder=str(Path(__file__).parent / "templates"),
        static_folder=str(Path(__file__).parent / "static"),
        static_url_path="/static",
    )
    application.config["SECRET_KEY"] = os.environ.get("FLASK_SECRET_KEY", os.urandom(24).hex())

    # Auth
    init_auth(application, dev=dev)

    # Analytics (GDPR-compliant, no cookies)
    analytics_db = str(_project_root / "data" / "analytics.db")
    init_analytics(application, db_path=analytics_db)

    # Register blueprints
    register_blueprints(application)

    # Database lifecycle (per-request)
    @application.teardown_appcontext
    def close_db(exception=None):
        database = g.pop("db", None)
        if database is not None:
            database.close()

    # Error handlers
    @application.errorhandler(404)
    def not_found(e):
        return render_template("errors/404.html"), 404

    @application.errorhandler(500)
    def server_error(e):
        return render_template("errors/500.html"), 500

    # Request timing
    @application.before_request
    def start_timer():
        g.start_time = time.time()

    @application.after_request
    def set_security_headers(response):
        response.headers["X-Content-Type-Options"] = "nosniff"
        response.headers["X-Frame-Options"] = "DENY"
        response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
        if hasattr(g, "start_time"):
            duration = (time.time() - g.start_time) * 1000
            logger = logging.getLogger("webui")
            logger.info("%s %s %s %.1fms", request.method, request.path,
                        response.status_code, duration)
        return response

    return application


# Lazy module-level app for backward compatibility (import from webui.app import app)
# Don't eagerly create — let __main__ or the importer control dev mode.
app: Flask | None = None


def get_app(dev: bool = False) -> Flask:
    """Get or create the app singleton."""
    global app
    if app is None:
        app = create_app(dev=dev)
    return app


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="IETF Draft Analyzer Web UI")
    parser.add_argument("--dev", action="store_true",
                        help="Development mode: enables admin features (gaps, monitor, compare, annotations)")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=5000)
    args = parser.parse_args()

    app = create_app(dev=args.dev)

    mode = "\033[33mDEV\033[0m (admin enabled)" if args.dev else "\033[32mPRODUCTION\033[0m (admin disabled)"
    print(f"Starting IETF Draft Analyzer — {mode}")
    print(f"  http://{args.host}:{args.port}")
    if args.dev:
        print("  Admin features: gaps, monitor, compare, annotations, AI synthesis")
    app.run(debug=args.dev, host=args.host, port=args.port)
