# [DEF:backend.src.scripts.create_admin:Module]
#
# @TIER:      STANDARD
# @SEMANTICS: admin, setup, user, auth, cli
# @PURPOSE:   CLI tool for creating the initial admin user.
# @LAYER:     Scripts
# @RELATION:  USES -> backend.src.core.auth.security
# @RELATION:  USES -> backend.src.core.database
# @RELATION:  USES -> backend.src.models.auth
#
# @INVARIANT: Admin user must have the "Admin" role.

# [SECTION: IMPORTS]
import sys
import argparse
from pathlib import Path

# Add src to path
sys.path.append(str(Path(__file__).parent.parent.parent))

from src.core.database import AuthSessionLocal, init_db
from src.core.auth.security import get_password_hash
from src.models.auth import User, Role
from src.core.logger import logger, belief_scope
# [/SECTION]

# [DEF:create_admin:Function]
# @PURPOSE: Creates an admin user and necessary roles/permissions.
# @PRE:     username and password provided via CLI.
# @POST:    Admin user exists in auth.db.
#
# @PARAM:   username (str) - Admin username.
# @PARAM:   password (str) - Admin password.
def create_admin(username, password):
    with belief_scope("create_admin"):
        db = AuthSessionLocal()
        try:
            # 1. Ensure Admin role exists
            admin_role = db.query(Role).filter(Role.name == "Admin").first()
            if not admin_role:
                logger.info("Creating Admin role...")
                admin_role = Role(name="Admin", description="System Administrator")
                db.add(admin_role)
                db.commit()
                db.refresh(admin_role)

            # 2. Check if user already exists
            existing_user = db.query(User).filter(User.username == username).first()
            if existing_user:
                logger.warning(f"User {username} already exists.")
                return

            # 3. Create Admin user
            logger.info(f"Creating admin user: {username}")
            new_user = User(
                username=username,
                password_hash=get_password_hash(password),
                auth_source="LOCAL",
                is_active=True
            )
            new_user.roles.append(admin_role)
            db.add(new_user)
            db.commit()
            logger.info(f"Admin user {username} created successfully.")
            
        except Exception as e:
            logger.error(f"Failed to create admin user: {e}")
            db.rollback()
        finally:
            db.close()
# [/DEF:create_admin:Function]

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Create initial admin user")
    parser.add_argument("--username", required=True, help="Admin username")
    parser.add_argument("--password", required=True, help="Admin password")
    args = parser.parse_args()
    
    # Ensure DB is initialized before creating admin
    init_db()
    create_admin(args.username, args.password)

# [/DEF:backend.src.scripts.create_admin:Module]