#!/usr/bin/env python3
"""Reproduce a controlled FIFO acceptance-logic defect and the existing correction.
This is a mutation exercise, not a claim about a historical production bug.
"""
from pathlib import Path
import os, subprocess, sys, tempfile, hashlib
ROOT=Path(__file__).resolve().parents[1]
output=Path(sys.argv[1] if len(sys.argv)>1 else '/tmp/admo-fifo-debug');output.mkdir(parents=True,exist_ok=True)
source=ROOT/'projects/fifo-rtl/rtl/sync_fifo.sv';bench=ROOT/'projects/fifo-rtl/tb/tb_sync_fifo.sv'
correct=source.read_text();needle='wire take_write = wr_en && (!full || take_read);'
assert correct.count(needle)==1
faulty=correct.replace(needle,'wire take_write = wr_en && !full;')
results=[]
for label,text in [('faulty',faulty),('corrected',correct)]:
 folder=output/label;folder.mkdir(exist_ok=True)
 dut=folder/'sync_fifo.sv';dut.write_text(text)
 cmd=[os.environ.get('IVERILOG','iverilog')]
 if os.environ.get('IVERILOG_BACKEND'):cmd+=['-B'+os.environ['IVERILOG_BACKEND']]
 cmd+=['-g2012','-s','tb_sync_fifo','-Ptb_sync_fifo.DEPTH=4','-Ptb_sync_fifo.DATA_WIDTH=8','-o',str(folder.resolve()/'test.vvp'),str(dut.resolve()),str(bench)]
 subprocess.run(cmd,check=True,capture_output=True,text=True)
 run=subprocess.run([os.environ.get('VVP','vvp'),'test.vvp'],cwd=folder,capture_output=True,text=True)
 raw=(run.stdout+run.stderr).replace(str(ROOT),'<repo>').replace(str(output),'<output>')
 (folder/'result.txt').write_text(raw)
 if label=='faulty':assert run.returncode!=0 and 'expected count/full/empty/data=4/1/0/1 actual=3/0/0/1' in raw,raw
 else:assert run.returncode==0 and 'PASS sync_fifo WIDTH=8 DEPTH=4 cycles=823' in raw,raw
 results += [f'[{label}] exit={run.returncode}',raw.strip()]
report='''FIFO controlled debugging exercise
Original DUT SHA-256: '''+hashlib.sha256(source.read_bytes()).hexdigest()+'''
Method: deliberately remove the full+read exception from take_write.
The independent scoreboard and stimulus are unchanged in both runs.
This is a reproducible mutation exercise, not historical bug-discovery evidence.

'''+ '\n\n'.join(results)+'\n\nPASS defective logic rejected; existing corrected logic passes\n'
(output/'summary.txt').write_text(report);print(report)
