import { describe, it, expect } from 'vitest';
import { extractStreamingField, CONTENT_FIELD } from './streamFieldExtract';

describe('extractStreamingField', () => {
  it('extracts Write content from complete args', () => {
    const raw = '{"path":"output/x.html","content":"<h1>Hi</h1>"}';
    expect(extractStreamingField('Write', raw)).toBe('<h1>Hi</h1>');
  });

  it('extracts Edit new_string', () => {
    const raw = '{"file_path":"a.ts","old_string":"foo","new_string":"bar","replace_all":false}';
    expect(extractStreamingField('Edit', raw)).toBe('bar');
  });

  it('returns the decoded prefix for an unterminated (still-streaming) value', () => {
    const raw = '{"path":"x","content":"line1\\nline2 and more';
    expect(extractStreamingField('Write', raw)).toBe('line1\nline2 and more');
  });

  it('survives a chunk boundary that splits an escape', () => {
    // trailing lone backslash must not corrupt output; decode stops before it
    const raw = '{"content":"ab\\';
    expect(extractStreamingField('Write', raw)).toBe('ab');
  });

  it('survives a chunk boundary that splits a \\uXXXX escape', () => {
    const raw = '{"content":"emoji \\u26';
    expect(extractStreamingField('Write', raw)).toBe('emoji ');
  });

  it('returns empty string before the target field appears', () => {
    expect(extractStreamingField('Write', '{"path":"x","con')).toBe('');
  });

  it('does not false-match on key-like text inside another field value', () => {
    const raw = '{"path":"a\\"content\\":\\"FAKE","content":"REAL"}';
    expect(extractStreamingField('Write', raw)).toBe('REAL');
  });

  it('keeps quotes and braces that appear inside the HTML value', () => {
    const raw = '{"content":"<div class=\\"a\\">{x}</div>"}';
    expect(extractStreamingField('Write', raw)).toBe('<div class="a">{x}</div>');
  });

  it('returns empty for tools not in the content-field map', () => {
    expect(extractStreamingField('Read', '{"file_path":"x"}')).toBe('');
  });

  it('maps Write to content and Edit to new_string', () => {
    expect(CONTENT_FIELD.Write).toBe('content');
    expect(CONTENT_FIELD.Edit).toBe('new_string');
  });
});
