import os

from flask import Flask, render_template
from flask_login import current_user
from dotenv import load_dotenv

# Load .env before config.py
load_dotenv()

from config import DevelopmentConfig, ProductionConfig
from .extensions import db, migrate, login_manager


def create_app():
    app = Flask(__name__)

    env = os.getenv("FLASK_ENV", "development")

    app.config.from_object(
        ProductionConfig
        if env == "production"
        else DevelopmentConfig
    )

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)

    login_manager.login_view = "auth.login"
    login_manager.login_message = "Please log in to continue."
    login_manager.login_message_category = "info"

    # Import models so Flask-Migrate discovers the complete schema.
    from . import models  # noqa: F401

    # Register blueprints.
    from .auth.routes import bp as auth_bp
    from .employee.routes import bp as employee_bp
    from .seva_bhaav.routes import bp as seva_bhaav_bp
    from .seva_daan.routes import bp as seva_daan_bp
    from .manager.routes import bp as manager_bp
    from .admin.routes import bp as admin_bp
    from .impact.routes import bp as impact_bp

    app.register_blueprint(auth_bp)
    app.register_blueprint(employee_bp)
    app.register_blueprint(seva_bhaav_bp)
    app.register_blueprint(seva_daan_bp)
    app.register_blueprint(manager_bp)
    app.register_blueprint(admin_bp)
    app.register_blueprint(impact_bp)

    @app.route("/")
    def index():
        from sqlalchemy import func
        from .models import Activity, DonationCause, Employee, HeartTransaction
        from .models.enums import ActivityStatus, CauseStatus

        activities = (
            Activity.query.filter_by(status=ActivityStatus.PUBLISHED)
            .order_by(Activity.start_datetime.asc())
            .limit(6)
            .all()
        )
        causes = (
            DonationCause.query.filter_by(status=CauseStatus.PUBLISHED)
            .order_by(DonationCause.created_at.desc())
            .limit(6)
            .all()
        )

        leaderboard = (
            db.session.query(
                Employee.full_name,
                Employee.employee_code,
                func.sum(HeartTransaction.hearts).label("hearts"),
            )
            .join(HeartTransaction, HeartTransaction.employee_id == Employee.id)
            .filter(Employee.is_active.is_(True))
            .group_by(Employee.id, Employee.full_name, Employee.employee_code)
            .order_by(func.sum(HeartTransaction.hearts).desc(), Employee.full_name.asc())
            .limit(5)
            .all()
        )

        # Leadership quotes should only be published once approved by Piramal.
        # These placeholders keep the homepage section ready without fabricating attribution.
        testimonials = [
            {
                "quote": "Approved leadership testimonial to be added here. This space can highlight why volunteering matters to Piramal's culture and communities.",
                "name": "Piramal Finance Leadership",
                "role": "Awaiting approved quote",
            },
            {
                "quote": "Approved leadership testimonial to be added here. This space can speak about employee participation and the power of collective action.",
                "name": "People & Culture Leadership",
                "role": "Awaiting approved quote",
            },
            {
                "quote": "Approved leadership testimonial to be added here. This space can connect Seva Setu with long-term social impact and purpose.",
                "name": "Business Leadership",
                "role": "Awaiting approved quote",
            },
        ]

        return render_template(
            "public/home.html",
            activities=activities,
            causes=causes,
            leaderboard=leaderboard,
            testimonials=testimonials,
        )

    @app.errorhandler(403)
    def forbidden(_error):
        return render_template("errors/403.html"), 403

    return app
