# app/core/lifespan.py
"""Application lifespan management - Clean Migration Approach.

This module provides classes and functions for:
- Application startup and shutdown events
- Logging setup
- Default user creation
- NO database table creation (handled by Alembic)
"""

import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from sqlalchemy import text

from middleware.auth import AuthManager

from .database import engine
from .logging import setup_logging

# Remove this import if not needed: from models.database.base import Base


logger = logging.getLogger(__name__)
auth_manager = AuthManager()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan events - Clean migration approach."""

    # === STARTUP ===
    app_logger = setup_logging()
    app_logger.info("Starting Wizamart multi-tenant platform")
    logger.info("[OK] Application startup completed")

    yield

    # === SHUTDOWN ===
    app_logger.info("Shutting down Wizamart platform")
    # Add cleanup tasks here if needed


# === NEW HELPER FUNCTION ===
def check_database_ready():
    """Check if database is ready (migrations have been run)."""
    try:
        with engine.connect() as conn:
            # Check for tables in the public schema (PostgreSQL)
            result = conn.execute(
                text(
                    "SELECT tablename FROM pg_catalog.pg_tables "
                    "WHERE schemaname = 'public' LIMIT 1"
                )
            )
            tables = result.fetchall()
            return len(tables) > 0
    except Exception:
        return False


def get_migration_status():
    """Get current Alembic migration status."""
    try:
        from alembic.config import Config

        alembic_cfg = Config("alembic.ini")

        # This would need more implementation to actually check status
        # For now, just return a placeholder
        return "Migration status check not implemented"
    except Exception as e:
        logger.warning(f"Could not check migration status: {e}")
        return "Unknown"


# === STARTUP VERIFICATION (Optional) ===
def verify_startup_requirements():
    """Verify that all startup requirements are met."""

    issues = []

    # Check if database exists and has tables
    if not check_database_ready():
        issues.append("Database not ready - run 'make migrate-up' first")

    # Add other checks as needed
    # - Configuration validation
    # - External service connectivity
    # - Required environment variables

    if issues:
        logger.error("[ERROR] Startup verification failed:")
        for issue in issues:
            logger.error(f"   - {issue}")
        return False

    logger.info("[OK] Startup verification passed")
    return True


# You can call this in your main.py if desired:
# if not verify_startup_requirements():
#     raise RuntimeError("Application startup requirements not met")
