const SNAPSHOT_VERSION = 1
const STORAGE_PREFIX = 'x-financial:assistant-session'

export const ASSISTANT_SESSION_SNAPSHOT_EVENT = 'x-financial-assistant-session-snapshot'

function normalizeSessionType(sessionType) {
  return String(sessionType || 'expense').trim() || 'expense'
}

function normalizeUserId(userId) {
  return String(userId || 'anonymous').trim() || 'anonymous'
}

export function resolveAssistantSessionSnapshotKey(userId, sessionType = 'expense') {
  return `${STORAGE_PREFIX}:${normalizeUserId(userId)}:${normalizeSessionType(sessionType)}`
}

function getStorage() {
  if (typeof window === 'undefined' || !window.localStorage) {
    return null
  }
  return window.localStorage
}

function emitSnapshotChange(sessionType, detail = {}) {
  if (typeof window === 'undefined') {
    return
  }
  window.dispatchEvent(new CustomEvent(ASSISTANT_SESSION_SNAPSHOT_EVENT, {
    detail: { sessionType: normalizeSessionType(sessionType), ...detail }
  }))
}

export function readAssistantSessionSnapshot(userId, sessionType = 'expense') {
  const storage = getStorage()
  if (!storage) {
    return null
  }

  try {
    const rawValue = storage.getItem(resolveAssistantSessionSnapshotKey(userId, sessionType))
    if (!rawValue) {
      return null
    }
    const parsed = JSON.parse(rawValue)
    if (!parsed || parsed.version !== SNAPSHOT_VERSION || !parsed.state) {
      return null
    }
    return parsed
  } catch (error) {
    console.warn('Failed to read assistant session snapshot:', error)
    return null
  }
}

export function writeAssistantSessionSnapshot(userId, sessionType = 'expense', state = {}) {
  const storage = getStorage()
  if (!storage) {
    return
  }

  const normalizedSessionType = normalizeSessionType(sessionType)
  const snapshot = {
    version: SNAPSHOT_VERSION,
    updatedAt: Date.now(),
    userId: normalizeUserId(userId),
    sessionType: normalizedSessionType,
    state
  }

  try {
    storage.setItem(
      resolveAssistantSessionSnapshotKey(userId, normalizedSessionType),
      JSON.stringify(snapshot)
    )
    emitSnapshotChange(normalizedSessionType)
  } catch (error) {
    console.warn('Failed to write assistant session snapshot:', error)
  }
}

export function clearAssistantSessionSnapshot(userId, sessionType = 'expense') {
  const storage = getStorage()
  if (!storage) {
    return false
  }

  const normalizedSessionType = normalizeSessionType(sessionType)
  try {
    storage.removeItem(resolveAssistantSessionSnapshotKey(userId, normalizedSessionType))
    emitSnapshotChange(normalizedSessionType, { action: 'clear' })
    return true
  } catch (error) {
    console.warn('Failed to clear assistant session snapshot:', error)
    return false
  }
}

export function hasAssistantSessionSnapshot(userId, sessionType = 'expense') {
  return Boolean(readAssistantSessionSnapshot(userId, sessionType)?.state)
}

function resolveSnapshotDraftClaimId(snapshot) {
  const state = snapshot?.state && typeof snapshot.state === 'object' ? snapshot.state : {}
  return String(state.draftClaimId || state.draft_claim_id || '').trim()
}

export function clearAssistantSessionSnapshotForDraftClaim(userId, claimId, sessionType = 'expense') {
  const normalizedClaimId = String(claimId || '').trim()
  if (!normalizedClaimId) {
    return false
  }

  const snapshot = readAssistantSessionSnapshot(userId, sessionType)
  if (resolveSnapshotDraftClaimId(snapshot) !== normalizedClaimId) {
    return false
  }

  return clearAssistantSessionSnapshot(userId, sessionType)
}
