import smtplib
from email.message import EmailMessage
import uuid

SMTP_HOST = "smtp.zoho.in"
SMTP_PORT = 465
SMTP_USER = "murali.krishna@genxi.in"
SMTP_PASS = "7XAY 7iqY Kyr3"

def send_welcome_email(to_email: str, company_name: str):
    msg = EmailMessage()
    msg["Subject"] = "Welcome to Our Platform!"
    msg["From"] = SMTP_USER
    msg["To"] = to_email
    msg.set_content(f"Hi {company_name},\n\nThanks for registering your company with us!")

    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp:
        smtp.starttls()
        smtp.login(SMTP_USER, SMTP_PASS)
        smtp.send_message(msg)



def generate_uuid():
    return str(uuid.uuid4())




from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import MetaData
from src.core.database import Base  # assuming all models are imported under Base
from sqlalchemy.pool import NullPool
from typing import List

async def init_dynamic_dbcreate(
    db_url: str,
    tables_to_skip: List[str] = None
):
    """
    Initializes a dynamic tenant database by creating only missing tables.
    Ensures existing tables (like companies) are not recreated but can still be referenced via FK.
    """
    engine = create_async_engine(db_url, poolclass=NullPool)

    metadata = Base.metadata
    reflected_metadata = MetaData()

    async with engine.begin() as conn:
        # Reflect existing tables into reflected_metadata
        await conn.run_sync(reflected_metadata.reflect)

        # Determine which tables to include (skip the ones already created)
        tables_to_include = [
            table for name, table in metadata.tables.items()
            if tables_to_skip is None or name not in tables_to_skip
        ]

        # Only create tables that are not already in the database
        missing_tables = [
            table for table in tables_to_include
            if table.name not in reflected_metadata.tables
        ]

        if missing_tables:
            print(f"Creating missing tables: {[t.name for t in missing_tables]}")
            await conn.run_sync(lambda sync_conn: metadata.create_all(sync_conn, tables=missing_tables))
        else:
            print("No missing tables to create.")
