"""Flask application entry point."""
from __future__ import annotations

import os
from flask import Flask, jsonify

from lawrisk.utils.env_loader import load_env
from lawrisk.middleware.smart_cors_middleware import init_smart_cors
from lawrisk.services.auth_service import (
    ensure_auth_schema,
    ensure_default_department_accounts,
    ensure_seed_admin,
)
from lawrisk.api.v2 import v2_bp
from lawrisk.api.auth import auth_bp


def create_app() -> Flask:
    """Create and configure Flask application."""
    # Load .env before creating app to make CORS/env configs available
    load_env()

    # Ensure auth schema and default accounts exist before serving
    try:
        ensure_auth_schema()
        ensure_seed_admin()
        ensure_default_department_accounts()
    except Exception:
        # Do not block app start; errors will surface on first request
        pass

    app = Flask(__name__)
    app.secret_key = os.getenv("FLASK_SECRET_KEY", "change-me")
    app.config.setdefault("SESSION_COOKIE_HTTPONLY", True)
    app.config.setdefault("SESSION_COOKIE_SAMESITE", "Lax")

    # Configure logging for immediate output
    import logging
    import sys

    # Create handler that outputs to stdout
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s [%(levelname)s] %(name)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    handler.setFormatter(formatter)

    # Configure root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    root_logger.addHandler(handler)

    # Disable Flask's default logger to avoid duplicate messages
    app.logger.handlers.clear()
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.INFO)

    # Enable CORS using existing middleware
    init_smart_cors(app)

    # Register blueprints
    app.register_blueprint(auth_bp)
    app.register_blueprint(v2_bp)

    # Basic health check
    @app.get("/healthz")
    def healthz():
        return jsonify({"status": "ok"})

    app.logger.info("=" * 80)
    app.logger.info("Flask application starting...")
    app.logger.info("=" * 80)
    app.logger.info("Registered routes:")
    for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
        methods = ",".join(sorted(rule.methods - {"HEAD", "OPTIONS"}))
        app.logger.info("  %s -> %s", rule.rule, methods)
    app.logger.info("=" * 80)

    return app


if __name__ == "__main__":
    port = int(os.getenv("PORT", "8000"))
    app = create_app()
    app.run(host="0.0.0.0", port=port, debug=True)
