import type { JsonObject, JsonRecord } from '../types/json.js'
import { asJsonObject, isPlainObject } from '../types/json.js'
import type { TaskContext } from '../types/task-context.js'

export type { JsonRecord, JsonObject }

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

  if (isPlainObject(value)) {
    return value
  }

  try {
    const parsed = JSON.parse(String(value || '{}')) as unknown
    return asJsonObject(parsed)
  } catch {
    return {}
  }
}

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

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