local EnsureApiRegistry = rawget(_G, "LIDCOUNCIL_EnsureApiRegistry")
local API, INTERNAL_API
if type(EnsureApiRegistry) == "function" then
  API, INTERNAL_API = EnsureApiRegistry()
else
  API = rawget(_G, "LIDCOUNCIL_API")
  if type(API) ~= "table" then
    API = {}
    _G.LIDCOUNCIL_API = API
  end
  if type(API.__internal) ~= "table" then
    API.__internal = {}
  end
  INTERNAL_API = API.__internal
end

INTERNAL_API.LIDCOUNCIL_CreateCoreSystemProfileOps_Impl = function(deps)
  deps = type(deps) == "table" and deps or {}

  local TrimText = deps.TrimText
  local RootDB = deps.RootDB

  local function NormalizeLootProfileIdPart(value, fallback)
    local part = string.lower(TrimText(value))
    part = part:gsub("%s+", "_")
    part = part:gsub("[^%w_%-%:]", "")
    if part == "" then
      part = tostring(fallback or "profile")
    end
    return part
  end

  local function BuildKnownLootProfileIdSet(root, skippedProfile)
    local known = {}
    root = type(root) == "table" and root or RootDB()
    for _, profile in pairs(root.profiles or {}) do
      if type(profile) == "table" and profile ~= skippedProfile and type(profile.meta) == "table" then
        local profileId = TrimText(profile.meta.profileId)
        if profileId ~= "" then
          known[string.lower(profileId)] = true
        end
      end
    end
    return known
  end

  local function GenerateLootProfileId(root, creatorKey, profileName, skippedProfile)
    root = type(root) == "table" and root or RootDB()
    root.__profileIdCounter = math.max(0, tonumber(root.__profileIdCounter) or 0)

    local knownIds = BuildKnownLootProfileIdSet(root, skippedProfile)
    local creatorPart = NormalizeLootProfileIdPart(creatorKey, "unknown")
    local profilePart = NormalizeLootProfileIdPart(profileName, "profile")
    local createdAt = tonumber(time and time() or 0) or 0

    while true do
      root.__profileIdCounter = root.__profileIdCounter + 1
      local randomPart = math.random(100000, 999999)
      local candidate = string.format("%s:%d:%d:%d:%s", creatorPart, createdAt, root.__profileIdCounter, randomPart, profilePart)
      if not knownIds[string.lower(candidate)] then
        return candidate
      end
    end
  end

  local function EnsureLootProfileIdentity(profile, profileName, fallbackCreatorKey, rootOverride)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}

    local profileId = TrimText(profile.meta.profileId)
    if profileId == "" then
      local creatorKey = TrimText(fallbackCreatorKey)
      if creatorKey == "" then
        creatorKey = TrimText(profile.meta.createdBy)
      end
      local permissions = type(profile.meta.permissions) == "table" and profile.meta.permissions or nil
      if creatorKey == "" and permissions then
        creatorKey = TrimText(permissions.master)
      end
      profile.meta.profileId = GenerateLootProfileId(rootOverride or RootDB(), creatorKey, profileName, profile)
    end

    return profile.meta.profileId
  end

  local function AssignNewLootProfileIdentity(profile, profileName, fallbackCreatorKey, rootOverride)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}

    local creatorKey = TrimText(fallbackCreatorKey)
    if creatorKey == "" then
      creatorKey = TrimText(profile.meta.createdBy)
    end
    local permissions = type(profile.meta.permissions) == "table" and profile.meta.permissions or nil
    if creatorKey == "" and permissions then
      creatorKey = TrimText(permissions.master)
    end

    profile.meta.profileId = GenerateLootProfileId(rootOverride or RootDB(), creatorKey, profileName, profile)
    return profile.meta.profileId
  end

  local function EnsureLootProfileSyncState(profile)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}
    profile.meta.sync = type(profile.meta.sync) == "table" and profile.meta.sync or {}
    local syncState = profile.meta.sync
    syncState.mode = TrimText(syncState.mode)
    if syncState.mode == "" then
      syncState.mode = "LOCAL"
    end
    syncState.origin = TrimText(syncState.origin)
    if syncState.origin == "" then
      syncState.origin = "CREATE"
    end
    syncState.cloneSourceProfileId = TrimText(syncState.cloneSourceProfileId)
    syncState.cloneSourceProfileName = TrimText(syncState.cloneSourceProfileName)
    syncState.cloneCreatedAt = tonumber(syncState.cloneCreatedAt) or nil
    syncState.sharedSourceProfileId = TrimText(syncState.sharedSourceProfileId)
    syncState.sharedSourceProfileName = TrimText(syncState.sharedSourceProfileName)
    syncState.sharedSourceCharacter = TrimText(syncState.sharedSourceCharacter)
    syncState.sharedAppliedAt = tonumber(syncState.sharedAppliedAt) or nil
    return syncState
  end

  local function MarkLootProfileAsIndependentClone(profile, origin, sourceInfo)
    profile = type(profile) == "table" and profile or {}
    local syncState = EnsureLootProfileSyncState(profile)
    sourceInfo = type(sourceInfo) == "table" and sourceInfo or {}

    syncState.mode = "LOCAL"
    syncState.origin = TrimText(origin)
    if syncState.origin == "" then
      syncState.origin = "CREATE"
    end
    syncState.cloneSourceProfileId = TrimText(sourceInfo.profileId)
    syncState.cloneSourceProfileName = TrimText(sourceInfo.profileName)
    syncState.cloneCreatedAt = tonumber(time and time() or 0) or 0
    syncState.sharedSourceProfileId = ""
    syncState.sharedSourceProfileName = ""
    syncState.sharedSourceCharacter = ""
    syncState.sharedAppliedAt = nil
    return syncState
  end

  local function MarkLootProfileAsSharedReplica(profile, origin, sourceInfo)
    profile = type(profile) == "table" and profile or {}
    local syncState = EnsureLootProfileSyncState(profile)
    sourceInfo = type(sourceInfo) == "table" and sourceInfo or {}

    syncState.mode = "SHARED"
    syncState.origin = TrimText(origin)
    if syncState.origin == "" then
      syncState.origin = "SESSION_SNAPSHOT"
    end
    syncState.sharedSourceProfileId = TrimText(sourceInfo.profileId)
    syncState.sharedSourceProfileName = TrimText(sourceInfo.profileName)
    syncState.sharedSourceCharacter = TrimText(sourceInfo.sourceCharacter)
    syncState.sharedAppliedAt = tonumber(time and time() or 0) or 0
    return syncState
  end

  local function EnsureLootProfileRevisionState(profile)
    profile = type(profile) == "table" and profile or {}
    profile.meta = profile.meta or {}
    profile.meta.domainRevisions = type(profile.meta.domainRevisions) == "table" and profile.meta.domainRevisions or {}

    local currentRevision = math.max(0, tonumber(profile.meta.revision) or 0)
    local currentUpdatedAt = tonumber(profile.meta.updatedAt) or tonumber(profile.meta.createdAt) or (time and time() or 0)
    local domainRevisions = profile.meta.domainRevisions

    local function ensureDomain(domainKey)
      local entry = type(domainRevisions[domainKey]) == "table" and domainRevisions[domainKey] or {}
      entry.revision = math.max(0, tonumber(entry.revision) or currentRevision)
      entry.updatedAt = tonumber(entry.updatedAt) or currentUpdatedAt
      domainRevisions[domainKey] = entry
      return entry
    end

    ensureDomain("settings")
    ensureDomain("permissions")
    ensureDomain("operational")
    ensureDomain("loot")
    ensureDomain("session")
    return domainRevisions
  end

  local function NormalizeLootProfileDomainKey(domain)
    local resolved = string.lower(TrimText(domain))
    if resolved == "settings" then
      return "settings"
    end
    if resolved == "permissions" then
      return "permissions"
    end
    if resolved == "loot" then
      return "loot"
    end
    if resolved == "session" then
      return "session"
    end
    return "operational"
  end

  local function GetLootProfileDomainRevision(profile, domain)
    if type(profile) ~= "table" then
      return 0
    end
    local domainKey = NormalizeLootProfileDomainKey(domain)
    local domainRevisions = EnsureLootProfileRevisionState(profile)
    local entry = type(domainRevisions[domainKey]) == "table" and domainRevisions[domainKey] or {}
    return math.max(0, tonumber(entry.revision) or 0)
  end

  return {
    EnsureLootProfileIdentity = EnsureLootProfileIdentity,
    AssignNewLootProfileIdentity = AssignNewLootProfileIdentity,
    EnsureLootProfileSyncState = EnsureLootProfileSyncState,
    MarkLootProfileAsIndependentClone = MarkLootProfileAsIndependentClone,
    MarkLootProfileAsSharedReplica = MarkLootProfileAsSharedReplica,
    EnsureLootProfileRevisionState = EnsureLootProfileRevisionState,
    NormalizeLootProfileDomainKey = NormalizeLootProfileDomainKey,
    GetLootProfileDomainRevision = GetLootProfileDomainRevision,
  }
end
