# #region SeedPermissionsScript [C:5] [TYPE Module] [SEMANTICS rbac, search, auth]
#
# @BRIEF Populates the auth database with initial system permissions.
# @LAYER Infrastructure
# @RELATION DEPENDS_ON -> AuthSessionLocal
# @RELATION DEPENDS_ON -> Permission
# @RELATION DEPENDS_ON -> Role
# @RELATION DEPENDS_ON -> AuthRepository
#
# @INVARIANT  Safe to run multiple times (idempotent).
# @SIDE_EFFECT  Writes permissions to database
# @DATA_CONTRACT  CLIArgs -> SeedSummary

from pathlib import Path
import sys

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

from src.core.auth.repository import AuthRepository
from src.core.cot_logger import seed_trace_id
from src.core.database import AuthSessionLocal
from src.core.logger import belief_scope, logger
from src.models.auth import Permission, Role

# #region INITIAL_PERMISSIONS [C:3] [TYPE Constant]
# @BRIEF Canonical bootstrap permission tuples seeded into auth storage.
# @RELATION DEPENDS_ON -> SeedPermissionsScript
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"},
    # Dataset Review Permissions
    {"resource": "dataset:session", "action": "READ"},
    {"resource": "dataset:session", "action": "MANAGE"},
    {"resource": "dataset:session", "action": "APPROVE"},
    {"resource": "dataset:execution", "action": "PREVIEW"},
    {"resource": "dataset:execution", "action": "LAUNCH"},
    {"resource": "dataset:execution", "action": "LAUNCH_PROD"},
]
# #endregion INITIAL_PERMISSIONS


# #region seed_permissions [C:3] [TYPE Function]
# @BRIEF Inserts missing permissions into the database.
# @POST     All INITIAL_PERMISSIONS exist in the DB.
# @RELATION DEPENDS_ON -> AuthSessionLocal
# @RELATION DEPENDS_ON -> Permission
# @RELATION DEPENDS_ON -> Role
# @RELATION DEPENDS_ON -> AuthRepository
# @RELATION DEPENDS_ON -> INITIAL_PERMISSIONS
def seed_permissions():
    seed_trace_id()
    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"),
                ("dataset:session", "READ"),
                ("dataset:session", "MANAGE"),
                ("dataset:execution", "PREVIEW"),
                ("dataset:execution", "LAUNCH"),
            ]

            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()


# #endregion seed_permissions

if __name__ == "__main__":
    seed_permissions()

# #endregion SeedPermissionsScript
