import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { POST } from '@/app/api/chat/route'
import { NextRequest } from 'next/server'
import { resetFlagsCache } from '@/lib/flags'

// Mock fetch globally
global.fetch = vi.fn()

describe('Diff Tool - Disabled Flag', () => {
  const originalEnv = { ...process.env }

  beforeEach(() => {
    resetFlagsCache()
    vi.clearAllMocks()

    // Set up agent but disable diff tool
    process.env.AGENT_1_URL = 'https://example.com/webhook/test'
    process.env.IMAGE_UPLOADS_ENABLED = 'true'
    process.env.DIFF_TOOL_ENABLED = 'false'
  })

  afterEach(() => {
    process.env = { ...originalEnv }
    resetFlagsCache()
  })

  it('converts diff tool calls to plain markdown when flag is disabled', async () => {
    const mockResponse = JSON.stringify({
      type: 'tool_call',
      name: 'show_diff',
      args: {
        oldCode: 'const x = 1;\nconsole.log(x);',
        newCode: 'const x = 2;\nconsole.log(x);',
        title: 'Update Variable',
        language: 'javascript',
      },
    })

    ;(global.fetch as any).mockResolvedValueOnce({
      ok: true,
      status: 200,
      text: async () => mockResponse,
    })

    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Show me the changes',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(200)

    // Should NOT contain diff-tool markdown
    expect(data.response).not.toContain('```diff-tool')

    // Should contain plain markdown instead
    expect(data.response).toContain('### Update Variable')
    expect(data.response).toContain('**Before:**')
    expect(data.response).toContain('**After:**')
    expect(data.response).toContain('```javascript')
    expect(data.response).toContain('const x = 1')
    expect(data.response).toContain('const x = 2')
  })

  it('handles streaming diff tool calls when disabled', async () => {
    const mockResponse = `{"type":"item","content":"Here are the changes:\\n"}
{"type":"tool_call","name":"show_diff","args":{"oldCode":"old","newCode":"new","title":"Changes","language":"text"}}`

    ;(global.fetch as any).mockResolvedValueOnce({
      ok: true,
      status: 200,
      text: async () => mockResponse,
    })

    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Show diff',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(200)
    expect(data.response).toContain('Here are the changes:')
    expect(data.response).not.toContain('```diff-tool')
    expect(data.response).toContain('**Before:**')
    expect(data.response).toContain('**After:**')
  })

  it('uses default title when not provided', async () => {
    const mockResponse = JSON.stringify({
      type: 'tool_call',
      name: 'show_diff',
      args: {
        oldCode: 'before',
        newCode: 'after',
        // No title provided
        language: 'text',
      },
    })

    ;(global.fetch as any).mockResolvedValueOnce({
      ok: true,
      status: 200,
      text: async () => mockResponse,
    })

    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Show diff',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(200)
    expect(data.response).toContain('### Code Changes')
  })

  it('handles regular text responses normally', async () => {
    const mockResponse = JSON.stringify({
      response: 'This is a normal text response without any diff tool calls.',
    })

    ;(global.fetch as any).mockResolvedValueOnce({
      ok: true,
      status: 200,
      text: async () => mockResponse,
    })

    const request = new NextRequest('http://localhost:3000/api/chat', {
      method: 'POST',
      body: JSON.stringify({
        message: 'Hello',
        agentId: 'agent-1',
        sessionId: 'test-session',
        timestamp: new Date().toISOString(),
      }),
    })

    const response = await POST(request)
    const data = await response.json()

    expect(response.status).toBe(200)
    expect(data.response).toBe('This is a normal text response without any diff tool calls.')
  })
})
