from pathlib import Path
import subprocess
import tempfile

root = Path(__file__).resolve().parents[2]
out = root / 'research' / 'reviews'
original = (root / 'examples/test/contracts.test.ts').read_text()

with tempfile.TemporaryDirectory(prefix='pi-reviewer-c-negative-') as raw:
    temp = Path(raw)
    (temp / 'test').mkdir()
    (temp / 'src').symlink_to(root / 'examples/src', target_is_directory=True)
    (temp / 'node_modules').symlink_to(root / 'examples/node_modules', target_is_directory=True)
    (temp / 'package.json').write_text('{"type":"module"}')
    mutations = {
        'sequential': (
            original.replace(', executionMode: "sequential"', ''),
            'mixed batch'),
        'listener': (
            original.replace('agent.subscribe(async (event) => {',
                'agent.subscribe((event) => { void (async () => {')
                .replace('  });\n  let settled = false;\n  const run',
                '  })(); });\n  let settled = false;\n  const run'),
            '等待 agent_end'),
        'budget': (
            original.replace('  agent.finishTurn = budget.finishTurn;',
                             '  // Negative control: omit the shared turn budget.'),
            '真实Core预算'),
    }
    for name, (content, pattern) in mutations.items():
        assert content != original
        path = temp / 'test' / f'{name}.test.ts'
        path.write_text(content)
        result = subprocess.run(['node', '--test', '--test-reporter', 'spec',
                                 f'--test-name-pattern={pattern}', str(path)],
                                cwd=temp, text=True, capture_output=True, timeout=30)
        log = result.stdout + result.stderr
        (out / f'reviewer-c-negative-{name}.txt').write_text(log)
        assert result.returncode != 0, f'{name}: mutation unexpectedly passed'
        assert 'AssertionError' in log, f'{name}: failed for a setup error'
        assert 'fail 1' in log, f'{name}: did not run intended test'
        print(f'{name}: intended assertion rejects mutated behavior, exit={result.returncode}')

    code_original = (root / 'examples/test/codemode.test.ts').read_text()
    code_mutation = code_original.replace('      Object.assign(committed, result.storeWrites.set);',
                                         '      // Negative control: omit host commit.')
    assert code_original != code_mutation
    path = temp / 'test' / 'store.test.ts'
    path.write_text(code_mutation)
    result = subprocess.run(['node', '--test', '--test-reporter', 'spec',
                             '--test-name-pattern=成功 store', str(path)],
                            cwd=temp, text=True, capture_output=True, timeout=30)
    log = result.stdout + result.stderr
    (out / 'reviewer-c-negative-store.txt').write_text(log)
    assert result.returncode != 0 and 'AssertionError' in log and 'fail 1' in log
    print(f'store: intended assertion rejects missing commit, exit={result.returncode}')

    resources_original = (root / 'examples/src/research-resources.ts').read_text()
    resources_mutation = resources_original.replace(', { projectTrusted: false }', '') \
        .replace('    systemPromptOverride: () => undefined,\n', '')
    assert resources_original != resources_mutation
    (temp / 'test/resources-regressed.ts').write_text(resources_mutation)
    edges = (root / 'examples/test/edge-cases.test.ts').read_text() \
        .replace('../src/research-resources.ts', './resources-regressed.ts')
    path = temp / 'test/resources.test.ts'
    path.write_text(edges)
    result = subprocess.run(['node', '--test', '--test-reporter', 'spec',
                             '--test-name-pattern=实际SDK资源配置', str(path)],
                            cwd=temp, text=True, capture_output=True, timeout=30)
    log = result.stdout + result.stderr
    (out / 'reviewer-c-negative-resources.txt').write_text(log)
    assert result.returncode != 0 and 'AssertionError' in log and 'UNTRUSTED_SYSTEM_SENTINEL' in log
    print(f'resources: intended assertion rejects re-enabled project SYSTEM, exit={result.returncode}')
