import logging
import os
import uuid
import time
from logging.handlers import TimedRotatingFileHandler
from flask import Flask, g, request
from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity, get_jwt

from app.config import config_by_name
from app.extensions import db, migrate, mail, jwt, init_cors


class RequestIdFilter(logging.Filter):
    def filter(self, record):
        record.request_id = getattr(g, "request_id", "-")
        return True


def configure_logging(app):
    log_level = app.config.get("LOG_LEVEL", "INFO")
    log_file = os.getenv("LOG_FILE", "app.log")

    formatter = logging.Formatter(
        "%(asctime)s %(levelname)s [%(request_id)s] %(message)s"
    )

    file_handler = TimedRotatingFileHandler(
        log_file, when="midnight", interval=1, backupCount=5, encoding="utf-8"
    )
    file_handler.setLevel(log_level)
    file_handler.setFormatter(formatter)
    file_handler.addFilter(RequestIdFilter())

    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_handler.setFormatter(formatter)
    console_handler.addFilter(RequestIdFilter())

    app.logger.setLevel(log_level)
    app.logger.addHandler(file_handler)
    app.logger.addHandler(console_handler)



def create_app(config_name=None):
    config_name = config_name or os.getenv("FLASK_ENV", "development")
    app = Flask(__name__)
    app.config.from_object(config_by_name.get(config_name, config_by_name["default"]))

    os.makedirs(app.config["UPLOAD_FOLDER"], exist_ok=True)

    configure_logging(app)

    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    jwt.init_app(app)
    init_cors(app)

    @app.before_request
    def add_request_id():
        g.request_id = request.headers.get("X-Request-Id", str(uuid.uuid4()))
        g.start_time = time.time()

    @app.after_request
    def track_activity(response):
        try:
            verify_jwt_in_request(optional=True)
            user_id = get_jwt_identity()
            if user_id:
                from app.services.tracking_service import log_activity
                session_id = get_jwt().get("session_id")
                response_time = (time.time() - g.start_time) * 1000 if getattr(g, "start_time", None) else None
                log_activity(
                    user_id=user_id,
                    session_id=session_id,
                    action="api_call",
                    endpoint=request.path,
                    method=request.method,
                    response_time=response_time,
                )
        except Exception:
            pass
        return response

    from app.api import api_bp
    app.register_blueprint(api_bp, url_prefix="/api/v1")

    from app.utils.errors import register_error_handlers
    register_error_handlers(app)

    return app
