"""
Linux BenchTools - Database Initialization
"""

import os
from app.db.base import Base, BasePeripherals
from app.db.session import engine, engine_peripherals
from app.core.config import settings


def init_db():
    """
    Initialize database:
    - Create all tables
    - Create upload directory if it doesn't exist
    """
    # Create upload directory
    os.makedirs(settings.UPLOAD_DIR, exist_ok=True)

    # Create database directory if using SQLite
    if "sqlite" in settings.DATABASE_URL:
        db_path = settings.DATABASE_URL.replace("sqlite:///", "")
        db_dir = os.path.dirname(db_path)
        if db_dir:
            os.makedirs(db_dir, exist_ok=True)

    # Create all tables for main database
    Base.metadata.create_all(bind=engine)

    print(f"✅ Main database initialized: {settings.DATABASE_URL}")
    print(f"✅ Upload directory created: {settings.UPLOAD_DIR}")

    # Initialize peripherals database if module is enabled
    if settings.PERIPHERALS_MODULE_ENABLED:
        init_peripherals_db()


def init_peripherals_db():
    """
    Initialize peripherals database:
    - Create all tables
    - Create upload directories
    - Import peripheral models
    """
    # Import models to register them
    from app.models.peripheral import (
        Peripheral, PeripheralPhoto, PeripheralDocument,
        PeripheralLink, PeripheralLoan
    )
    from app.models.location import Location
    from app.models.peripheral_history import PeripheralLocationHistory

    # Create peripherals upload directories
    os.makedirs(settings.PERIPHERALS_UPLOAD_DIR, exist_ok=True)
    os.makedirs(os.path.join(settings.PERIPHERALS_UPLOAD_DIR, "photos"), exist_ok=True)
    os.makedirs(os.path.join(settings.PERIPHERALS_UPLOAD_DIR, "documents"), exist_ok=True)
    os.makedirs(os.path.join(settings.PERIPHERALS_UPLOAD_DIR, "locations", "images"), exist_ok=True)
    os.makedirs(os.path.join(settings.PERIPHERALS_UPLOAD_DIR, "locations", "qrcodes"), exist_ok=True)

    # Create database directory if using SQLite
    if "sqlite" in settings.PERIPHERALS_DB_URL:
        db_path = settings.PERIPHERALS_DB_URL.replace("sqlite:///", "")
        db_dir = os.path.dirname(db_path)
        if db_dir:
            os.makedirs(db_dir, exist_ok=True)

    # Create all tables for peripherals database
    BasePeripherals.metadata.create_all(bind=engine_peripherals)

    print(f"✅ Peripherals database initialized: {settings.PERIPHERALS_DB_URL}")
    print(f"✅ Peripherals upload directories created: {settings.PERIPHERALS_UPLOAD_DIR}")
