import sys
sys.path.insert(0, "/var/www/html/metafoliadorv2")

from app.config import settings
from app.models.database import tenant_db_url_ctx


def resolve_tenant(host: str) -> dict | None:
    if host == settings.main_domain or host == "localhost" or host == "127.0.0.1":
        return None

    from app.models.main_database import MainSessionLocal
    from app.models.main_customer import Customer

    db = MainSessionLocal()
    try:
        customers = db.query(Customer).all()
        for customer in customers:
            expected_host = f"{customer.subdomain}.{settings.main_domain}"
            if host == expected_host or host == customer.custom_domain:
                return {
                    "db_url": customer.db_url,
                    "active": customer.active,
                    "subdomain": customer.subdomain,
                }
        return None
    finally:
        db.close()


def is_main_domain(host: str) -> bool:
    return host == settings.main_domain
