export type JsonRecord = Record<string, any>

export function parseJsonObject(value: unknown): JsonRecord {
  if (!value) {
    return {}
  }

  if (typeof value === 'object' && !Array.isArray(value)) {
    return value as JsonRecord
  }

  try {
    const parsed = JSON.parse(String(value || '{}'))
    return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
  } catch {
    return {}
  }
}

export function parseTaskContext(task: { context_json?: unknown } | null | undefined): JsonRecord {
  return parseJsonObject(task?.context_json)
}

export function parseTaskState(task: { state_json?: unknown } | null | undefined): JsonRecord {
  return parseJsonObject(task?.state_json)
}
