#!/usr/bin/env python3
"""Creates the default tenant and admin user if they do not exist."""
import sys
import os

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from dotenv import load_dotenv
load_dotenv()

from app.core.database import SessionLocal
from app.core.models import Tenant, TenantStatus, User, UserRole, UserStatus
from app.core.security import hash_password


def main():
    admin_password = os.getenv("ADMIN_PASSWORD", "")
    if len(admin_password) < 12:
        raise RuntimeError("ADMIN_PASSWORD must be set to at least 12 characters")

    company_code = os.getenv("DEFAULT_TENANT_CODE", "platform")

    db = SessionLocal()
    try:
        tenant = db.query(Tenant).filter(Tenant.company_code == company_code).first()
        if not tenant:
            tenant = Tenant(
                company_code=company_code,
                name=os.getenv("DEFAULT_TENANT_NAME", "Platform Administration"),
                status=TenantStatus.active,
            )
            db.add(tenant)
            db.flush()
            print(f"Tenant created: {company_code}")
        else:
            print(f"Tenant already exists: {company_code}")

        existing = db.query(User).filter(
            User.username == "admin", User.tenant_id == tenant.id
        ).first()
        if existing:
            print("Admin user already exists.")
            db.commit()
            return

        admin = User(
            tenant_id=tenant.id,
            username="admin",
            password_hash=hash_password(admin_password),
            display_name="Administrator",
            role=UserRole.admin,
            status=UserStatus.active,
        )
        db.add(admin)
        db.commit()
        print(f"Admin user created: admin (tenant: {company_code})")
    finally:
        db.close()


if __name__ == "__main__":
    main()
