# [DEF:backend.src.scripts.seed_permissions:Module]
#
# @SEMANTICS: setup, database, auth, permissions, seeding
# @PURPOSE:   Populates the auth database with initial system permissions.
# @LAYER:     Scripts
# @RELATION:  USES -> backend.src.core.database.get_auth_db
# @RELATION:  USES -> backend.src.models.auth.Permission
#
# @INVARIANT: Safe to run multiple times (idempotent).

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

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

from src.core.database import AuthSessionLocal
from src.models.auth import Permission, Role
from src.core.auth.repository import AuthRepository
from src.core.logger import logger, belief_scope
# [/SECTION]

# [DEF:INITIAL_PERMISSIONS:Constant]
INITIAL_PERMISSIONS = [
    # Admin Permissions
    {"resource": "admin:users", "action": "READ"},
    {"resource": "admin:users", "action": "WRITE"},
    {"resource": "admin:roles", "action": "READ"},
    {"resource": "admin:roles", "action": "WRITE"},
    {"resource": "admin:settings", "action": "READ"},
    {"resource": "admin:settings", "action": "WRITE"},
    {"resource": "environments", "action": "READ"},
    {"resource": "plugins", "action": "READ"},
    {"resource": "tasks", "action": "READ"},
    {"resource": "tasks", "action": "WRITE"},
    
    # Plugin Permissions
    {"resource": "plugin:backup", "action": "EXECUTE"},
    {"resource": "plugin:migration", "action": "EXECUTE"},
    {"resource": "plugin:mapper", "action": "EXECUTE"},
    {"resource": "plugin:search", "action": "EXECUTE"},
    {"resource": "plugin:git", "action": "EXECUTE"},
    {"resource": "plugin:storage", "action": "EXECUTE"},
    {"resource": "plugin:storage", "action": "READ"},
    {"resource": "plugin:storage", "action": "WRITE"},
    {"resource": "plugin:debug", "action": "EXECUTE"},
    {"resource": "git_config", "action": "READ"},
]
# [/DEF:INITIAL_PERMISSIONS:Constant]

# [DEF:seed_permissions:Function]
# @PURPOSE: Inserts missing permissions into the database.
# @POST:    All INITIAL_PERMISSIONS exist in the DB.
def seed_permissions():
    with belief_scope("seed_permissions"):
        db = AuthSessionLocal()
        try:
            logger.info("Seeding permissions...")
            count = 0
            for perm_data in INITIAL_PERMISSIONS:
                exists = db.query(Permission).filter(
                    Permission.resource == perm_data["resource"],
                    Permission.action == perm_data["action"]
                ).first()
                
                if not exists:
                    new_perm = Permission(
                        resource=perm_data["resource"],
                        action=perm_data["action"]
                    )
                    db.add(new_perm)
                    count += 1
            
            db.commit()
            logger.info(f"Seeding completed. Added {count} new permissions.")

            # Assign permissions to User role
            repo = AuthRepository(db)
            user_role = repo.get_role_by_name("User")
            if not user_role:
                user_role = Role(name="User", description="Standard user with plugin access")
                db.add(user_role)
                db.flush()
            
            user_permissions = [
                ("plugin:mapper", "EXECUTE"),
                ("plugin:migration", "EXECUTE"),
                ("plugin:backup", "EXECUTE"),
                ("plugin:git", "EXECUTE"),
                ("plugin:storage", "READ"),
                ("plugin:storage", "WRITE"),
                ("environments", "READ"),
                ("plugins", "READ"),
                ("tasks", "READ"),
                ("tasks", "WRITE"),
                ("git_config", "READ"),
            ]

            for res, act in user_permissions:
                perm = repo.get_permission_by_resource_action(res, act)
                if perm and perm not in user_role.permissions:
                    user_role.permissions.append(perm)
            
            db.commit()
            logger.info("User role permissions updated.")

        except Exception as e:
            logger.error(f"Failed to seed permissions: {e}")
            db.rollback()
        finally:
            db.close()
# [/DEF:seed_permissions:Function]

if __name__ == "__main__":
    seed_permissions()

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