"""
Database initialization for StarPunk
"""

import sqlite3
from pathlib import Path
from starpunk.database.schema import INITIAL_SCHEMA_SQL


def init_db(app=None):
    """
    Initialize database schema and run migrations

    Args:
        app: Flask application instance (optional, for config access)
    """
    if app:
        db_path = app.config["DATABASE_PATH"]
        logger = app.logger
    else:
        # Fallback to default path
        db_path = Path("./data/starpunk.db")
        logger = None

    # Ensure parent directory exists
    db_path.parent.mkdir(parents=True, exist_ok=True)

    # Create database and initial schema
    conn = sqlite3.connect(db_path)
    try:
        conn.executescript(INITIAL_SCHEMA_SQL)
        conn.commit()
        if logger:
            logger.info(f"Database initialized: {db_path}")
        else:
            # Fallback logging when logger not available (e.g., during testing)
            import logging
            logging.getLogger(__name__).info(f"Database initialized: {db_path}")
    finally:
        conn.close()

    # Run migrations
    from starpunk.migrations import run_migrations
    run_migrations(db_path, logger=logger)
