import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { extractPermit, extractRateConfirmation } from '@/lib/adapters/flask'
import { extractionFailureReason } from '@/lib/observability/extraction-error-log'

let tempDirectory = ''

async function logPath(): Promise<string> {
  tempDirectory = await mkdtemp(path.join(os.tmpdir(), 'extraction-errors-'))
  const file = path.join(tempDirectory, 'errors.jsonl')
  vi.stubEnv('EXTRACTION_ERROR_LOG_FILE', file)
  vi.stubEnv('HHA_API_BASE_URL', 'https://gpt.test')
  vi.spyOn(console, 'error').mockImplementation(() => undefined)
  return file
}

afterEach(async () => {
  vi.restoreAllMocks()
  vi.unstubAllEnvs()
  vi.unstubAllGlobals()
  if (tempDirectory) await rm(tempDirectory, { recursive: true, force: true })
  tempDirectory = ''
})

describe('Permit and RateCon failure file', () => {
  it('keeps GPT terminal code and request ID for a failed permit', async () => {
    const file = await logPath()
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
      error: 'Permit extraction failed', code: 'unreadable_file', request_id: 'req-123',
    }), { status: 422, headers: { 'Content-Type': 'application/json' } })))
    const result = await extractPermit(new Blob(['%PDF-test']), 'permit.pdf')
    expect(result).toMatchObject({ ok: false, code: 'unreadable_file', httpStatus: 422, requestId: 'req-123' })
    expect(JSON.parse((await readFile(file, 'utf8')).trim())).toMatchObject({
      reason: 'unreadable_file', request_id: 'req-123', http_status: 422,
    })
  })

  it('logs a classified GPT permit failure without recording provider text, URL, or secret', async () => {
    const file = await logPath()
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
      error: 'Permit extraction failed',
      details: 'Groq API: Connection error at https://private.test/file?token=secret-value',
    }), { status: 500, headers: { 'Content-Type': 'application/json' } })))

    const result = await extractPermit(new Blob(['%PDF-test']), 'permit.pdf', {
      tripId: 'trip-1', documentId: 'doc-1', permitId: 'permit-1', sourceUrl: 'https://private.test/permit.pdf',
    })
    expect(result).toMatchObject({ ok: false, error: 'Backend responded 500' })
    const line = (await readFile(file, 'utf8')).trim()
    const record = JSON.parse(line)
    expect(record).toMatchObject({
      kind: 'permit', stage: 'gpt_api', trip_id: 'trip-1', document_id: 'doc-1',
      permit_id: 'permit-1', http_status: 500, reason: 'groq_connection_error',
      upstream_error: 'permit_extraction_failed',
    })
    expect(line).not.toMatch(/private\.test|secret-value|permit\.pdf|Connection error/)
  })

  it('logs RateCon authorization errors in the same file', async () => {
    const file = await logPath()
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'Unauthorized' }), {
      status: 403, headers: { 'Content-Type': 'application/json' },
    })))

    const result = await extractRateConfirmation(new Blob(['%PDF-test']), 'ratecon.pdf', {
      tripId: 'trip-2', documentId: 'doc-2',
    })
    expect(result).toMatchObject({ ok: false, error: 'Backend responded 403' })
    const record = JSON.parse((await readFile(file, 'utf8')).trim())
    expect(record).toMatchObject({
      kind: 'ratecon', stage: 'gpt_api', trip_id: 'trip-2', document_id: 'doc-2',
      http_status: 403, reason: 'gpt_auth_denied', upstream_error: 'unauthorized',
    })
  })

  it('keeps the HTTP status when GPT returns an HTML 500 instead of JSON', async () => {
    const file = await logPath()
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('<html>Internal Server Error</html>', {
      status: 500, headers: { 'Content-Type': 'text/html' },
    })))
    const result = await extractPermit(new Blob(['%PDF-test']), 'permit.pdf')
    expect(result).toMatchObject({ ok: false, error: 'Backend responded 500' })
    const line = (await readFile(file, 'utf8')).trim()
    expect(JSON.parse(line)).toMatchObject({ kind: 'permit', http_status: 500, reason: 'gpt_server_error' })
    expect(line).not.toContain('<html>')
  })

  it('logs network failure type without saving the exception message', async () => {
    const file = await logPath()
    vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('fetch failed: https://private.test/?api_key=secret')))
    const result = await extractRateConfirmation(new Blob(['%PDF-test']), 'ratecon.pdf')
    expect(result.ok).toBe(false)
    const line = (await readFile(file, 'utf8')).trim()
    expect(JSON.parse(line)).toMatchObject({ kind: 'ratecon', reason: 'gpt_connection_error', http_status: null })
    expect(line).not.toMatch(/private\.test|api_key|secret|fetch failed/)
  })

  it('classifies a no-data GPT response without exposing its raw details', () => {
    expect(extractionFailureReason({ kind: 'permit', stage: 'gpt_api', httpStatus: 500,
      upstreamError: 'Permit extraction produced no data' })).toBe('no_extractable_data')
  })
})
