from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy import text
from app.models import Base
import os
from dotenv import load_dotenv

load_dotenv()

DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///./stock_analysis.db")

engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)

async def init_db():
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
        
        # Migration: Add ai_model column if it doesn't exist (for SQLite)
        try:
            await conn.execute(
                text("ALTER TABLE reports ADD COLUMN ai_model VARCHAR(100) DEFAULT 'gemini-2.0-flash-exp'")
            )
            print("Migration: Added ai_model column to reports table")
        except Exception as e:
            # Column already exists or other error
            if "duplicate column" not in str(e).lower() and "already exists" not in str(e).lower():
                print(f"Migration check: {e}")

        # Migration: Add token columns to report_sections
        columns_to_add = [
            ("prompt_tokens", "INTEGER DEFAULT 0"),
            ("completion_tokens", "INTEGER DEFAULT 0"),
            ("total_tokens", "INTEGER DEFAULT 0")
        ]
        
        for col_name, col_type in columns_to_add:
            try:
                await conn.execute(text(f"ALTER TABLE report_sections ADD COLUMN {col_name} {col_type}"))
                print(f"Migration: Added {col_name} to report_sections table")
            except Exception as e:
                # SQLite error for duplicate column usually contains "duplicate column name"
                if "duplicate column" not in str(e).lower() and "already exists" not in str(e).lower():
                     print(f"Migration check for {col_name}: {e}")

async def get_db():
    async with AsyncSessionLocal() as session:
        yield session
