import type {ExtractCrumbDraft} from '@crumbs/core/schemas'
import {useCallback, useState} from 'react'

import {ApiError, cleanError} from '@/lib/errors'
import {
  extractCrumbFromImage,
  extractCrumbsFromUrl,
  MissingLlmKeyError,
} from '@/lib/extract'
import type {PendingShare} from '@/lib/pending-share'

export type ExtractOutcome =
  | {status: 'pending'}
  | {status: 'drafts'; drafts: ExtractCrumbDraft[]}
  | {status: 'missing-key'}
  | {status: 'error'; message: string}

const PENDING: ExtractOutcome = {status: 'pending'}

export const useExtractDraft = (share: PendingShare) => {
  const [outcome, setOutcome] = useState<ExtractOutcome>(PENDING)

  const run = useCallback(async () => {
    setOutcome(PENDING)
    try {
      const drafts =
        share.kind === 'image'
          ? await extractCrumbFromImage({uri: share.uri})
          : await extractCrumbsFromUrl(share.url)
      setOutcome({status: 'drafts', drafts})
    } catch (err) {
      const needsKey =
        err instanceof MissingLlmKeyError ||
        (err instanceof ApiError && err.code === 'invalid_llm_key')
      setOutcome(
        needsKey
          ? {status: 'missing-key'}
          : {
              status: 'error',
              message: cleanError(
                err,
                'Something went wrong reading your share.',
              ),
            },
      )
    }
  }, [share])

  return {outcome, run}
}
