# core/database.py

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
# core/database.py

"""from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.pool import NullPool
from fastapi import Request, HTTPException,Depends
from sqlalchemy import select
from azure.storage.filedatalake import DataLakeServiceClient
from src.core.database import async_session



#DATABASE_URL = "postgresql+asyncpg://finsightai_admin:finsightai123@91.108.104.205:5432/finsightai_db"
#from urllib.parse import quote_plus
# URL-encode the password (special character @ needs encoding)
# password = "Pankaj@123"
# encoded_password = quote_plus(password)

# Main database connection
#DATABASE_URL = f"postgresql+asyncpg://postgre:{encoded_password}@127.0.0.1:5432/demodb"

DATABASE_URL = "postgresql+asyncpg://avnadmin:AVNS_As15bncmWPRJZ26soQA@pg-185d6b1c-mavengroup-9e06.l.aivencloud.com:19481/postgres"
engine = create_async_engine(DATABASE_URL, pool_pre_ping=True)

AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    autocommit=False,
    autoflush=False,
    expire_on_commit=False
)

Base = declarative_base()

# Dependency
async def get_db():
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()




async def get_config(request: Request):
    from src.models.company import Company  # Keep this inside to avoid circular import
    from ..common.dependencies import get_current_company_user
    # Manually create the session
    async with AsyncSessionLocal() as db:

        # Get the Authorization header
        auth_header = request.headers.get("Authorization")
        print(auth_header)
        if not auth_header or not auth_header.startswith("Bearer "):
            
            raise HTTPException(status_code=401, detail="Invalid or missing Authorization token")

        # Extract the Bearer token
        token = auth_header.removeprefix("Bearer ").strip()

        # Decode token
        user = get_current_company_user(token)

        # Query Company
        stmt = select(Company).where(Company.id == user.company_id)
        result = await db.execute(stmt)
        company = result.scalar_one_or_none()

        if company is None:
            raise HTTPException(status_code=404, detail="Tenant not found")

        tenant_config = {
            "db_name": company.db_name,
            "db_host": "fpna-dev-postgresql.postgres.database.azure.com",
            "db_port": "5432",
            "db_user": "adminfpna",
            "db_password": "Maven%404321",
        }
        print("tent:",tenant_config)
        return tenant_config




async def get_db_on_the_fly(request: Request):
   
    config = await get_config(request)

    db_url = (
        f"postgresql+asyncpg://{config['db_user']}:{config['db_password']}"
        f"@{config['db_host']}:{config['db_port']}/{config['db_name']}"
    )

    # Create engine with NullPool to disable pooling
    engine = create_async_engine(
        db_url,
        poolclass=NullPool
    )

    # Create a new sessionmaker bound to this engine
    AsyncSessionLocal = sessionmaker(
        bind=engine,
        class_=AsyncSession,
        expire_on_commit=False,
    )

    async with AsyncSessionLocal() as session:
        yield session 


AZURE_STORAGE_ACCOUNT_NAME = "fpnainsightsdemo"
AZURE_STORAGE_KEY = "6MaaD8Ho6bDP9bErAWE3YWHMvQz5NnBQtOdosyE+p5XM7iEwEe4lXWqWKnYdMvbNCe5aNIqFP5xv+AStaxQzRw=="


ACCOUNT_URL = f"https://{AZURE_STORAGE_ACCOUNT_NAME}.dfs.core.windows.net"

 



def get_datalake_client():
    return DataLakeServiceClient(
        account_url=f"https://{AZURE_STORAGE_ACCOUNT_NAME}.dfs.core.windows.net",
        credential=AZURE_STORAGE_KEY
    )
    )"""









from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.pool import NullPool
from fastapi import Request, HTTPException,Depends
from sqlalchemy import select
from sqlalchemy import MetaData
from azure.storage.filedatalake import DataLakeServiceClient

AZURE_STORAGE_ACCOUNT_NAME = "fpnainsightsdemo"
AZURE_STORAGE_KEY = "6MaaD8Ho6bDP9bErAWE3YWHMvQz5NnBQtOdosyE+p5XM7iEwEe4lXWqWKnYdMvbNCe5aNIqFP5xv+AStaxQzRw=="


ACCOUNT_URL = f"https://{AZURE_STORAGE_ACCOUNT_NAME}.dfs.core.windows.net"

 



def get_datalake_client():
    return DataLakeServiceClient(
        account_url=f"https://{AZURE_STORAGE_ACCOUNT_NAME}.dfs.core.windows.net",
        credential=AZURE_STORAGE_KEY
    )




#DATABASE_URL = "postgresql+asyncpg://finsightai_admin:finsightai123@91.108.104.205:5432/finsightai_db"
#from urllib.parse import quote_plus
# URL-encode the password (special character @ needs encoding)
# password = "Pankaj@123"
# encoded_password = quote_plus(password)

# Main database connection
#DATABASE_URL = f"postgresql+asyncpg://postgre:{encoded_password}@127.0.0.1:5432/demodb"

DATABASE_URL = "postgresql+asyncpg://avnadmin:AVNS_As15bncmWPRJZ26soQA@pg-185d6b1c-mavengroup-9e06.l.aivencloud.com:19481/postgres"

engine = create_async_engine(DATABASE_URL, echo=True)

# Metadata object required for reflection
metadata = MetaData()

# Async session factory
async_session = sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False
)

AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    autocommit=False,
    autoflush=False,
    expire_on_commit=False
)

Base = declarative_base()
# Dependency
async def get_db():
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()



async def get_config(request: Request):
    from src.models.company import Company  # Keep this inside to avoid circular import
    from ..common.dependencies import get_current_company_user
    # Manually create the session
    async with AsyncSessionLocal() as db:

        # Get the Authorization header
        auth_header = request.headers.get("Authorization")
        print(auth_header)
        if not auth_header or not auth_header.startswith("Bearer "):
            
            raise HTTPException(status_code=401, detail="Invalid or missing Authorization token")

        # Extract the Bearer token
        token = auth_header.removeprefix("Bearer ").strip()

        # Decode token
        user = get_current_company_user(token)

        # Query Company
        stmt = select(Company).where(Company.id == user.company_id)
        result = await db.execute(stmt)
        company = result.scalar_one_or_none()

        if company is None:
            raise HTTPException(status_code=404, detail="Tenant not found")

        tenant_config = {
            "db_name": company.db_name,
            "db_host": "fpna-dev-postgresql.postgres.database.azure.com",
            "db_port": "5432",
            "db_user": "adminfpna",
            "db_password": "Maven%404321",
        }
        print("tent:",tenant_config)
        return tenant_config




async def get_db_on_the_fly(request: Request):
   
    config = await get_config(request)

    db_url = (
        f"postgresql+asyncpg://{config['db_user']}:{config['db_password']}"
        f"@{config['db_host']}:{config['db_port']}/{config['db_name']}"
    )

    # Create engine with NullPool to disable pooling
    engine = create_async_engine(
        db_url,
        poolclass=NullPool
    )

    # Create a new sessionmaker bound to this engine
    AsyncSessionLocal = sessionmaker(
        bind=engine,
        class_=AsyncSession,
        expire_on_commit=False,
    )

    async with AsyncSessionLocal() as session:
        yield session


AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False
)

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