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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
#!/usr/bin/env python3
"""
EDA Tool Suite for CircuitQA-Tool Dataset Generation

Six analysis backends:
1. synthesis_tool: Yosys + ABC; gate counts and gate-count-based area/delay/power estimates
2. simulation_tool: Icarus Verilog; toggle rates and toggle coverage measured from the VCD waveform
3. graph_extractor: Yosys; CDFG/AIG/DFG graphs
4. static_analyzer: source structure analysis
5. optimization_advisor: rule-based recommendations and Yosys recipes per target metric
6. cross_stage_mapper: RTL-to-netlist name alignment

Each tool returns a JSON-serialisable dict.
"""

import os
import re
import json
import tempfile
import subprocess
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, asdict
import hashlib
import time

# Root of the local tool installation (oss-cad-suite/, incdir/); override with CIRCUITQA_ROOT.
TOOLS_ROOT = os.environ.get("CIRCUITQA_ROOT", os.path.expanduser("~/circuitqa"))


# ============================================================================
# Configuration
# ============================================================================

# Conda environment with EDA tools
CONDA_ENV = "eda"
CONDA_PATH = os.path.expanduser("~/miniconda3")

# Tool timeouts (seconds)
YOSYS_TIMEOUT = 120
VERILATOR_TIMEOUT = 60
IVERILOG_TIMEOUT = 60

# Technology library for area estimation (generic)
# Area units are in arbitrary units (AU) - relative comparisons only
GATE_AREAS = {
    '$_AND_': 1.0, '$_NAND_': 1.0, '$_OR_': 1.0, '$_NOR_': 1.0,
    '$_XOR_': 2.0, '$_XNOR_': 2.0, '$_NOT_': 0.5, '$_BUF_': 0.5,
    '$_ANDNOT_': 1.5, '$_ORNOT_': 1.5, '$_MUX_': 2.0,
    '$_DFF_P_': 4.0, '$_DFF_N_': 4.0, '$_DFFE_PP_': 5.0,
    '$_SDFF_PP0_': 5.0, '$_SDFF_PP1_': 5.0,
    '$_DLATCH_P_': 3.0, '$_DLATCH_N_': 3.0,
}

# Delay per gate type (ps) - simplified model
GATE_DELAYS = {
    '$_AND_': 50, '$_NAND_': 40, '$_OR_': 50, '$_NOR_': 40,
    '$_XOR_': 80, '$_XNOR_': 80, '$_NOT_': 20, '$_BUF_': 20,
    '$_ANDNOT_': 60, '$_ORNOT_': 60, '$_MUX_': 100,
    '$_DFF_P_': 150, '$_DFF_N_': 150, '$_DFFE_PP_': 160,
}


# ============================================================================
# Helper Functions
# ============================================================================


def _last_json(text):
    """Yosys prints log lines both before and after `stat -json` output, so the
    JSON is a substring, not a prefix or suffix. A greedy brace-to-brace regex
    produces invalid JSON and json.loads on the remainder fails with "Extra
    data" -- either way the parse silently fails and gate_count stays 0, which
    then gets written into ground-truth answers. Scan candidate starts and use
    raw_decode, which parses a prefix and ignores trailing text."""
    import json as _j
    dec = _j.JSONDecoder()
    for i in [m.start() for m in re.finditer(r"\{", text)]:
        try:
            d, _ = dec.raw_decode(text[i:])
        except Exception:
            continue
        if isinstance(d, dict) and "modules" in d:
            return d
    return None


def run_command(cmd: List[str], timeout: int = 60, cwd: str = None) -> Tuple[int, str, str]:
    """Run a shell command with timeout."""
    # Run in its own process group so that a timeout kills the tool itself
    # (yosys/abc/vvp), not only the wrapping shell; otherwise orphans keep running.
    import signal
    try:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             text=True, cwd=cwd, start_new_session=True)
        try:
            out, err = p.communicate(timeout=timeout)
            return p.returncode, out, err
        except subprocess.TimeoutExpired:
            try: os.killpg(p.pid, signal.SIGKILL)
            except Exception: pass
            p.communicate()
            return -1, "", f"Command timed out after {timeout}s"
    except Exception as e:
        return -2, "", str(e)


def run_with_conda(tool_cmd: str, timeout: int = 60, cwd: str = None) -> Tuple[int, str, str]:
    """Run an EDA tool. Tools are expected on PATH (oss-cad-suite)."""
    tool_cmd = f"export PATH={TOOLS_ROOT}/oss-cad-suite/bin:$PATH; " + tool_cmd
    return run_command(["bash", "-c", tool_cmd], timeout=timeout, cwd=cwd)


def write_temp_verilog(code: str, suffix: str = ".v") -> str:
    """Write Verilog code to a temporary file."""
    fd, path = tempfile.mkstemp(suffix=suffix)
    with os.fdopen(fd, 'w') as f:
        f.write(code)
    return path


def extract_module_name(verilog_code: str) -> Optional[str]:
    """Extract the first module name from Verilog code."""
    match = re.search(r'module\s+(\w+)', verilog_code)
    return match.group(1) if match else None


# ============================================================================
# Tool 1: Synthesis Tool
# ============================================================================

@dataclass
class SynthesisResult:
    """Result from synthesis_tool."""
    status: str
    area: float
    delay: float
    power: float  # Estimated from toggle activity
    gate_count: int
    cell_breakdown: Dict[str, int]
    wire_count: int
    wire_bits: int
    critical_path_estimate: float
    synthesis_log: str
    error: Optional[str] = None


def synthesis_tool(verilog_code: str, optimization_level: str = "medium",
                   target_technology: str = "generic") -> Dict[str, Any]:
    """
    Synthesize Verilog code and extract PPA metrics using Yosys + ABC.

    Args:
        verilog_code: Verilog source code
        optimization_level: "low", "medium", or "high"
        target_technology: Technology target (currently "generic" only)

    Returns:
        Dict with area, delay, power, gate_count, synthesis_log
    """
    # Write code to temp file
    temp_file = write_temp_verilog(verilog_code)
    module_name = extract_module_name(verilog_code) or "top"

    try:
        # Build Yosys script based on optimization level
        opt_passes = {
            "low": "opt",
            "medium": "opt; share; opt",
            "high": "opt; share; opt; freduce; opt; techmap; opt"
        }
        opt_cmd = opt_passes.get(optimization_level, opt_passes["medium"])

        # Yosys synthesis command
        yosys_script = f"""
read_verilog -I{TOOLS_ROOT}/incdir {temp_file}
hierarchy -top {module_name}
proc; {opt_cmd}
techmap
abc -g gates
opt_clean
stat -json
        """

        # Run Yosys
        yosys_cmd = f"yosys -p '{yosys_script}' 2>&1"
        returncode, stdout, stderr = run_with_conda(yosys_cmd, timeout=YOSYS_TIMEOUT)

        if returncode != 0:
            return asdict(SynthesisResult(
                status="error",
                area=0, delay=0, power=0, gate_count=0,
                cell_breakdown={}, wire_count=0, wire_bits=0,
                critical_path_estimate=0,
                synthesis_log=stdout + stderr,
                error=f"Yosys failed with code {returncode}"
            ))

        # Parse synthesis statistics from Yosys output
        cell_breakdown = {}
        gate_count = 0
        wire_count = 0
        wire_bits = 0

        # Try to parse JSON output first (stat -json format)
        try:
            # Find JSON block in output
            stat_json = _last_json(stdout)
            if stat_json:
                if 'modules' in stat_json:
                    for mod_name, mod_data in stat_json['modules'].items():
                        if 'num_cells_by_type' in mod_data:
                            for cell_type, count in mod_data['num_cells_by_type'].items():
                                cell_breakdown[cell_type] = count
                                gate_count += count
                        if 'num_wires' in mod_data:
                            wire_count = mod_data['num_wires']
                        if 'num_wire_bits' in mod_data:
                            wire_bits = mod_data['num_wire_bits']
        except (json.JSONDecodeError, KeyError):
            pass

        # Fallback: Parse text output if JSON parsing failed
        if gate_count == 0:
            for line in stdout.split('\n'):
                line = line.strip()
                # Match cell type lines like "  $_AND_    15"
                cell_match = re.match(r'(\$_\w+_)\s+(\d+)', line)
                if cell_match:
                    cell_type = cell_match.group(1)
                    count = int(cell_match.group(2))
                    cell_breakdown[cell_type] = count
                    gate_count += count

                # Match wire counts
                wire_match = re.match(r'Number of wires:\s+(\d+)', line)
                if wire_match:
                    wire_count = int(wire_match.group(1))

                bits_match = re.match(r'Number of wire bits:\s+(\d+)', line)
                if bits_match:
                    wire_bits = int(bits_match.group(1))

        # Calculate area estimate
        area = sum(GATE_AREAS.get(cell, 1.0) * count
                   for cell, count in cell_breakdown.items())

        # Estimate delay (critical path = longest chain)
        # Simplified: assume sqrt(gate_count) depth
        avg_delay = sum(GATE_DELAYS.get(cell, 50) * count
                        for cell, count in cell_breakdown.items()) / max(gate_count, 1)
        critical_path_estimate = avg_delay * (gate_count ** 0.3)

        # Estimate power (simplified: proportional to gate count and toggle)
        power = gate_count * 0.001  # mW estimate

        return asdict(SynthesisResult(
            status="success",
            area=round(area, 2),
            delay=round(critical_path_estimate, 2),
            power=round(power, 4),
            gate_count=gate_count,
            cell_breakdown=cell_breakdown,
            wire_count=wire_count,
            wire_bits=wire_bits,
            critical_path_estimate=round(critical_path_estimate, 2),
            synthesis_log=stdout[-2000:] if len(stdout) > 2000 else stdout
        ))

    finally:
        # Cleanup temp file
        if os.path.exists(temp_file):
            os.remove(temp_file)


# ============================================================================
# Tool 2: Simulation Tool
# ============================================================================

@dataclass
class SimulationResult:
    """Result from simulation_tool."""
    status: str
    toggle_rates: Dict[str, float]
    simulation_cycles: int
    assertion_results: Dict[str, bool]
    coverage_estimate: float
    signal_activity: Dict[str, Any]
    simulation_log: str
    error: Optional[str] = None


def _parse_ports(verilog_code: str, module_name: str):
    """(name, width or None) for the input and output ports of `module_name`."""
    m = re.search(r"\bmodule\s+" + re.escape(module_name) + r"\b(.*?)\bendmodule\b", verilog_code, re.S)
    body = m.group(1) if m else verilog_code
    def grab(kind):
        out = []
        for decl in re.finditer(kind + r"\s+(?:(?:wire|reg|logic|signed|unsigned)\s+)*(\[\s*(\d+)\s*:\s*(\d+)\s*\])?\s*([A-Za-z_][\w\s,]*?)\s*(?=[;)]|,\s*(?:input|output|inout)\b)", body):
            w = abs(int(decl.group(2)) - int(decl.group(3))) + 1 if decl.group(2) else (None if decl.group(1) else 1)
            for name in re.split(r"\s*,\s*", decl.group(4).strip()):
                if re.fullmatch(r"[A-Za-z_]\w*", name or "") and name not in ("wire", "reg", "logic", "signed", "unsigned"):
                    out.append((name, w))
        seen, res = set(), []
        for n, w in out:
            if n not in seen:
                seen.add(n); res.append((n, w))
        return res
    return grab(r"\binput\b"), grab(r"\boutput\b")


def _vcd_toggles(vcd_path: str, scope: str = "dut"):
    """Count 0<->1 bit transitions per variable of `scope` in a VCD file."""
    vars_, cur, ids = {}, [], {}
    with open(vcd_path, errors="ignore") as f:
        lines = f.read().split("\n")
    k = 0
    while k < len(lines):
        t = lines[k].split()
        if t[:1] == ["$scope"]:
            cur.append(t[2] if len(t) > 2 else "")
        elif t[:1] == ["$upscope"]:
            if cur: cur.pop()
        elif t[:1] == ["$var"] and cur and cur[-1] == scope and len(t) >= 5:
            width, code, name = int(t[2]), t[3], t[4]
            ids[code] = name
            vars_[name] = {"width": width, "toggles": 0, "bits_toggled": set()}
        elif t[:1] == ["$enddefinitions"]:
            k += 1
            break
        k += 1
    prev = {}
    for line in lines[k:]:
        if not line or line[0] in "#$":
            continue
        if line[0] in "01xzXZ":
            val, code = line[0], line[1:].strip()
        elif line[0] in "bB":
            parts = line[1:].split()
            if len(parts) != 2:
                continue
            val, code = parts
        else:
            continue
        if code not in ids:
            continue
        name = ids[code]; w = vars_[name]["width"]
        val = val.rjust(w, val[0] if val[0] in "xzXZ" else "0")[-w:]
        old = prev.get(code)
        if old is not None:
            for b, (o, n) in enumerate(zip(old, val)):
                if o in "01" and n in "01" and o != n:
                    vars_[name]["toggles"] += 1
                    vars_[name]["bits_toggled"].add(b)
        prev[code] = val
    return vars_


def simulation_tool(verilog_code: str, num_cycles: int = 100,
                    simulation_type: str = "functional") -> Dict[str, Any]:
    """
    Simulate the design with Icarus Verilog and measure switching activity.

    A generated testbench drives a detected clock (one period per cycle), holds any
    detected reset active for the first two cycles, and drives the remaining inputs
    with random values every cycle (fixed seed). The waveform of the top-level design
    signals is dumped to a VCD file, and the toggle rate of every signal is measured as
    the number of 0<->1 bit transitions divided by (bit width x cycles).
    `coverage_estimate` is the toggle coverage: the percentage of signal bits that
    toggled at least once. If the design does not compile or the run does not
    complete, the result has status "error" and carries no activity figures.
    """
    module_name = extract_module_name(verilog_code) or "top"
    inputs, outputs = _parse_ports(verilog_code, module_name)
    wires = re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)
    regs = re.findall(r'reg\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)
    activity = {"inputs": len(inputs), "outputs": len(outputs), "wires": len(wires), "regs": len(regs)}
    is_clk = lambda n: re.fullmatch(r"(?i)(a?clk\w*|\w*_clk|clock\w*|\w*_clock)", n) is not None
    is_rst = lambda n: re.search(r"(?i)(rst|reset)", n) is not None
    active_low = lambda n: re.search(r"(?i)(_n|_b|n)$", n) is not None
    def decl(kind, n, w):
        return f"{kind} {'' if not w or w == 1 else f'[{w-1}:0] '}{n};"
    clks = [n for n, _ in inputs if is_clk(n)]
    rsts = [n for n, _ in inputs if is_rst(n) and n not in clks]
    data = [(n, w) for n, w in inputs if n not in clks and n not in rsts]
    temp_dut = write_temp_verilog(verilog_code, suffix="_dut.v")
    temp_vvp = temp_dut.replace("_dut.v", ".vvp")
    temp_vcd = temp_dut.replace("_dut.v", ".vcd")
    tb = ["`timescale 1ns/1ps", f"module tb_{module_name};"]
    tb += ["    " + decl("reg", n, w) for n, w in inputs]
    tb += ["    " + decl("wire", n, w) for n, w in outputs]
    tb.append(f"    {module_name} dut(" + ", ".join(f".{n}({n})" for n, _ in inputs + outputs) + ");")
    tb.append("    integer cycle_count; integer seed;")
    tb.append("    initial begin")
    tb.append(f'        $dumpfile("{temp_vcd}"); $dumpvars(1, dut);')
    tb.append("        seed = 42; cycle_count = 0;")
    tb += [f"        {n} = 0;" for n in clks]
    tb += [f"        {n} = {0 if active_low(n) else 1};" for n in rsts]
    tb += [f"        {n} = 0;" for n, _ in data]
    tb.append(f"        repeat ({num_cycles}) begin")
    tb += [f"            {n} = $random(seed);" for n, _ in data]
    if rsts:
        tb.append("            if (cycle_count == 2) begin " + " ".join(f"{n} = {1 if active_low(n) else 0};" for n in rsts) + " end")
    if clks:
        tb += [f"            #5 {clks[0]} = 1;", f"            #5 {clks[0]} = 0;"]
    else:
        tb.append("            #10;")
    tb.append("            cycle_count = cycle_count + 1;")
    tb.append("        end")
    tb.append('        $display("SIMULATION_COMPLETE"); $display("CYCLES: %0d", cycle_count); $finish;')
    tb.append("    end")
    tb.append("endmodule")
    temp_tb = write_temp_verilog("\n".join(tb) + "\n", suffix="_tb.v")

    def fail(msg):
        return asdict(SimulationResult(status="error", toggle_rates={}, simulation_cycles=0, assertion_results={},
                                       coverage_estimate=0.0, signal_activity=activity,
                                       simulation_log=msg[:1000], error=msg[:300]))
    try:
        rc, out, err = run_with_conda(f"iverilog -g2012 -I{TOOLS_ROOT}/incdir -o {temp_vvp} {temp_dut} {temp_tb}",
                                      timeout=IVERILOG_TIMEOUT)
        if rc != 0:
            return fail(f"Compilation failed: {(err or out)[:500]}")
        rc, out, err = run_with_conda(f"vvp -n {temp_vvp}", timeout=IVERILOG_TIMEOUT)
        if "SIMULATION_COMPLETE" not in out or not os.path.exists(temp_vcd):
            return fail(f"Simulation did not complete: {(err or out)[-500:]}")
        m = re.search(r"CYCLES:\s*(\d+)", out)
        cycles = int(m.group(1)) if m else num_cycles
        v = _vcd_toggles(temp_vcd)
        if not v or not cycles:
            return fail("No waveform recorded for the design signals")
        rates = {n: round(d["toggles"] / (d["width"] * cycles), 3) for n, d in v.items()}
        bits = sum(d["width"] for d in v.values())
        hit = sum(len(d["bits_toggled"]) for d in v.values())
        activity["signals_recorded"] = len(v)
        activity["signals_toggling"] = sum(1 for d in v.values() if d["toggles"])
        return asdict(SimulationResult(status="success", toggle_rates=dict(sorted(rates.items())[:200]),
                                       simulation_cycles=cycles, assertion_results={},
                                       coverage_estimate=round(100.0 * hit / bits, 1) if bits else 0.0,
                                       signal_activity=activity, simulation_log=out[-1000:]))
    except Exception as e:
        return fail(f"Simulation error: {e}")
    finally:
        for p in (temp_dut, temp_tb, temp_vvp, temp_vcd):
            try:
                os.remove(p)
            except OSError:
                pass


# ============================================================================
# Tool 3: Graph Extractor
# ============================================================================

@dataclass
class GraphResult:
    """Result from graph_extractor."""
    status: str
    graph_type: str
    nodes: List[Dict[str, Any]]
    edges: List[Dict[str, Any]]
    node_count: int
    edge_count: int
    graph_properties: Dict[str, Any]
    error: Optional[str] = None


def graph_extractor(verilog_code: str, graph_type: str = "CDFG") -> Dict[str, Any]:
    """
    Extract graph representation from Verilog code using Yosys.

    Args:
        verilog_code: Verilog source code
        graph_type: "CDFG", "AIG", "AST", or "DFG"

    Returns:
        Dict with nodes, edges, node_count, edge_count, graph_properties
    """
    temp_file = write_temp_verilog(verilog_code)
    module_name = extract_module_name(verilog_code) or "top"
    temp_json = temp_file.replace(".v", ".json")

    try:
        # Build Yosys script based on graph type
        if graph_type == "AIG":
            # And-Inverter Graph
            yosys_script = f"""
read_verilog -I{TOOLS_ROOT}/incdir {temp_file}
hierarchy -top {module_name}
proc; opt; techmap
aigmap
write_json {temp_json}
stat
            """
        elif graph_type == "AST":
            # Abstract Syntax Tree - use basic parsing
            yosys_script = f"""
read_verilog -I{TOOLS_ROOT}/incdir {temp_file}
hierarchy -top {module_name}
write_json {temp_json}
stat
            """
        elif graph_type == "DFG":
            # Data Flow Graph
            yosys_script = f"""
read_verilog -I{TOOLS_ROOT}/incdir {temp_file}
hierarchy -top {module_name}
proc; opt
write_json {temp_json}
stat
            """
        else:  # CDFG - Control/Data Flow Graph
            yosys_script = f"""
read_verilog -I{TOOLS_ROOT}/incdir {temp_file}
hierarchy -top {module_name}
proc; opt; memory; opt
write_json {temp_json}
stat
            """

        # Run Yosys
        yosys_cmd = f"yosys -p '{yosys_script}' 2>&1"
        returncode, stdout, stderr = run_with_conda(yosys_cmd, timeout=YOSYS_TIMEOUT)

        if returncode != 0 or not os.path.exists(temp_json):
            return asdict(GraphResult(
                status="error",
                graph_type=graph_type,
                nodes=[], edges=[],
                node_count=0, edge_count=0,
                graph_properties={},
                error=f"Yosys failed: {stderr[:500]}"
            ))

        # Parse JSON output
        with open(temp_json, 'r') as f:
            yosys_json = json.load(f)

        # Extract nodes and edges from Yosys JSON format
        nodes = []
        edges = []

        if 'modules' in yosys_json:
            for mod_name, mod_data in yosys_json['modules'].items():
                # Extract cells as nodes
                if 'cells' in mod_data:
                    for cell_name, cell_data in mod_data['cells'].items():
                        nodes.append({
                            'id': cell_name,
                            'type': cell_data.get('type', 'unknown'),
                            'attributes': cell_data.get('attributes', {}),
                            'parameters': cell_data.get('parameters', {})
                        })

                        # Extract connections as edges
                        if 'connections' in cell_data:
                            for port, signals in cell_data['connections'].items():
                                for sig in signals if isinstance(signals, list) else [signals]:
                                    edges.append({
                                        'source': cell_name,
                                        'target': str(sig),
                                        'port': port
                                    })

                # Extract ports as nodes
                if 'ports' in mod_data:
                    for port_name, port_data in mod_data['ports'].items():
                        nodes.append({
                            'id': port_name,
                            'type': f"port_{port_data.get('direction', 'unknown')}",
                            'bits': port_data.get('bits', [])
                        })

        # Calculate graph properties
        node_types = {}
        for node in nodes:
            t = node.get('type', 'unknown')
            node_types[t] = node_types.get(t, 0) + 1

        return asdict(GraphResult(
            status="success",
            graph_type=graph_type,
            nodes=nodes[:100],  # Limit for large designs
            edges=edges[:200],
            node_count=len(nodes),
            edge_count=len(edges),
            graph_properties={
                'node_types': node_types,
                'avg_degree': round(len(edges) / max(len(nodes), 1), 2),
                'module_name': module_name
            }
        ))

    finally:
        for f in [temp_file, temp_json]:
            if os.path.exists(f):
                os.remove(f)




# ============================================================================
# Tool 4: Static Analyzer (Enhanced version)
# ============================================================================

@dataclass
class StaticAnalysisResult:
    """Result from static_analyzer."""
    status: str
    module_name: str
    port_count: Dict[str, int]
    signal_count: Dict[str, int]
    always_blocks: int
    assign_statements: int
    instantiations: List[str]
    code_complexity: Dict[str, Any]
    lint_warnings: List[str]
    error: Optional[str] = None


def static_analyzer(verilog_code: str, analysis_type: str = "full") -> Dict[str, Any]:
    """
    Perform static code analysis on Verilog code.

    Args:
        verilog_code: Verilog source code
        analysis_type: "full", "ports", "complexity", or "lint"

    Returns:
        Dict with module_name, port_count, signal_count, always_blocks, etc.
    """
    module_name = extract_module_name(verilog_code) or "unknown"

    # Count ports
    inputs = re.findall(r'input\s+(?:wire\s+)?(?:reg\s+)?(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)
    outputs = re.findall(r'output\s+(?:wire\s+)?(?:reg\s+)?(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)
    inouts = re.findall(r'inout\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)

    # Count signals
    wires = re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)
    regs = re.findall(r'reg\s+(?:\[\d+:\d+\])?\s*(\w+)', verilog_code)
    params = re.findall(r'parameter\s+(\w+)', verilog_code)
    localparam = re.findall(r'localparam\s+(\w+)', verilog_code)

    # Count blocks
    always_blocks = len(re.findall(r'always\s*@', verilog_code))
    always_comb = len(re.findall(r'always_comb', verilog_code))
    always_ff = len(re.findall(r'always_ff', verilog_code))
    assign_stmts = len(re.findall(r'\bassign\s+', verilog_code))

    # Find instantiations
    instantiations = re.findall(r'(\w+)\s+\w+\s*\(', verilog_code)
    # Filter out keywords
    keywords = {'module', 'function', 'task', 'if', 'else', 'case', 'for', 'while', 'begin', 'end'}
    instantiations = [i for i in instantiations if i not in keywords and not i.startswith('$')]

    # Calculate complexity metrics
    lines = verilog_code.split('\n')
    code_lines = [l for l in lines if l.strip() and not l.strip().startswith('//')]

    # Cyclomatic complexity estimate
    branches = len(re.findall(r'\b(if|else|case|for|while)\b', verilog_code))

    # Lint warnings
    lint_warnings = []

    # Check for blocking assignments in sequential blocks
    if re.search(r'always\s*@\s*\(\s*posedge.*=(?!=)', verilog_code):
        lint_warnings.append("Potential blocking assignment in sequential block")

    # Check for latches (incomplete if/case)
    if re.search(r'always\s*@\s*\*', verilog_code):
        if not re.search(r'else\b', verilog_code):
            lint_warnings.append("Combinational block may infer latch (missing else)")

    # Check for unused signals (simplified)
    all_signals = set(wires + regs)
    used_signals = set(re.findall(r'\b(\w+)\b', verilog_code))

    return asdict(StaticAnalysisResult(
        status="success",
        module_name=module_name,
        port_count={
            'inputs': len(inputs),
            'outputs': len(outputs),
            'inouts': len(inouts),
            'total': len(inputs) + len(outputs) + len(inouts)
        },
        signal_count={
            'wires': len(wires),
            'regs': len(regs),
            'parameters': len(params) + len(localparam),
            'total': len(wires) + len(regs)
        },
        always_blocks=always_blocks + always_comb + always_ff,
        assign_statements=assign_stmts,
        instantiations=list(set(instantiations))[:20],
        code_complexity={
            'lines_of_code': len(code_lines),
            'total_lines': len(lines),
            'cyclomatic_complexity': branches + 1,
            'nesting_depth': verilog_code.count('begin'),
            'operator_count': len(re.findall(r'[+\-*/&|^~<>=]', verilog_code))
        },
        lint_warnings=lint_warnings[:10]
    ))



# ============================================================================
# Tool 5: Optimization Advisor
# ============================================================================

@dataclass
class OptimizationResult:
    """Result from optimization_advisor."""
    status: str
    target_metric: str
    recommended_recipes: List[str]
    optimization_suggestions: List[Dict[str, Any]]
    estimated_improvement: Dict[str, float]
    trade_offs: List[str]
    error: Optional[str] = None


# Synthesis recipes for different optimization targets
SYNTHESIS_RECIPES = {
    'area': [
        "synth -top {module} -flatten",
        "opt -full; share -aggressive; opt",
        "abc -g gates -liberty {lib}",
        "opt_clean -purge"
    ],
    'delay': [
        "synth -top {module}",
        "opt -fast",
        "abc -fast -liberty {lib}",
        "opt_clean"
    ],
    'power': [
        "synth -top {module}",
        "opt; share; opt",
        "abc -g gates -liberty {lib}",
        "opt_clean; clockgate"
    ],
    'balanced': [
        "synth -top {module}",
        "opt; techmap; opt",
        "abc -liberty {lib}",
        "opt_clean"
    ]
}


def optimization_advisor(verilog_code: str, target_metric: str = "area",
                         constraints: Dict[str, Any] = None) -> Dict[str, Any]:
    """
    Provide optimization recommendations for Verilog code.

    Args:
        verilog_code: Verilog source code
        target_metric: "area", "delay", "power", or "balanced"
        constraints: Optional timing/area constraints

    Returns:
        Dict with recommended_recipes, optimization_suggestions, estimated_improvement
    """
    module_name = extract_module_name(verilog_code) or "top"

    # Analyze code patterns
    has_memories = bool(re.search(r'reg\s*\[\d+:\d+\]\s*\w+\s*\[\d+:\d+\]', verilog_code))
    has_fsm = bool(re.search(r'case\s*\(.*state', verilog_code, re.IGNORECASE))
    has_arithmetic = bool(re.search(r'[+\-*/]', verilog_code))
    has_mux = bool(re.search(r'\?.*:', verilog_code)) or bool(re.search(r'case\s*\(', verilog_code))

    # Count complexity indicators
    always_count = len(re.findall(r'always\s*@', verilog_code))
    reg_count = len(re.findall(r'\breg\b', verilog_code))

    # Build recommendations
    suggestions = []
    trade_offs = []
    estimated_improvement = {}

    if target_metric == "area":
        if has_memories:
            suggestions.append({
                'type': 'memory_optimization',
                'description': 'Consider using memory inference for large arrays',
                'command': 'memory -nomap; memory_bram'
            })
        if has_mux:
            suggestions.append({
                'type': 'mux_optimization',
                'description': 'Share multiplexers where possible',
                'command': 'muxcover; opt'
            })
        if has_arithmetic:
            suggestions.append({
                'type': 'resource_sharing',
                'description': 'Share arithmetic operators',
                'command': 'share -aggressive'
            })
        estimated_improvement = {'area': -15.0, 'delay': 5.0, 'power': -10.0}
        trade_offs = ["Area optimization may increase delay", "Aggressive sharing increases routing complexity"]

    elif target_metric == "delay":
        if has_arithmetic:
            suggestions.append({
                'type': 'pipeline_insertion',
                'description': 'Consider pipelining arithmetic operations',
                'command': 'Use register retiming'
            })
        if has_fsm:
            suggestions.append({
                'type': 'fsm_encoding',
                'description': 'Use one-hot encoding for faster FSM',
                'command': 'fsm_opt; fsm_recode -encoding one-hot'
            })
        suggestions.append({
            'type': 'logic_duplication',
            'description': 'Duplicate logic to reduce fanout',
            'command': 'splitnets -driver'
        })
        estimated_improvement = {'area': 10.0, 'delay': -20.0, 'power': 5.0}
        trade_offs = ["Speed optimization increases area", "Higher power consumption"]

    elif target_metric == "power":
        suggestions.append({
            'type': 'clock_gating',
            'description': 'Insert clock gating for registers',
            'command': 'clockgate'
        })
        if has_memories:
            suggestions.append({
                'type': 'memory_banking',
                'description': 'Bank memories to reduce active area',
                'command': 'memory_share'
            })
        suggestions.append({
            'type': 'operand_isolation',
            'description': 'Isolate operands when not in use',
            'command': 'Use enable signals for arithmetic'
        })
        estimated_improvement = {'area': 5.0, 'delay': 5.0, 'power': -25.0}
        trade_offs = ["Power optimization may add area overhead", "Clock gating adds timing complexity"]

    else:  # balanced
        suggestions.append({
            'type': 'balanced_optimization',
            'description': 'Use default synthesis flow',
            'command': 'synth -top {module}'
        })
        estimated_improvement = {'area': -5.0, 'delay': -5.0, 'power': -5.0}
        trade_offs = ["Balanced approach may not achieve best results in any single metric"]

    # Get recipes
    recipes = SYNTHESIS_RECIPES.get(target_metric, SYNTHESIS_RECIPES['balanced'])
    recipes = [r.format(module=module_name, lib="stdcells.lib") for r in recipes]

    return asdict(OptimizationResult(
        status="success",
        target_metric=target_metric,
        recommended_recipes=recipes,
        optimization_suggestions=suggestions,
        estimated_improvement=estimated_improvement,
        trade_offs=trade_offs
    ))



# ============================================================================
# Tool 6: Cross-Stage Mapper
# ============================================================================

@dataclass
class CrossStageResult:
    """Result from cross_stage_mapper."""
    status: str
    rtl_to_netlist_mapping: Dict[str, List[str]]
    alignment_score: float
    unmapped_elements: List[str]
    mapping_statistics: Dict[str, Any]
    error: Optional[str] = None


def cross_stage_mapper(rtl_code: str, netlist_code: str = None) -> Dict[str, Any]:
    """
    Map RTL signals to netlist elements.

    If netlist_code is not provided, synthesizes the RTL to generate netlist.

    Args:
        rtl_code: RTL Verilog source code
        netlist_code: Optional synthesized netlist code

    Returns:
        Dict with rtl_to_netlist_mapping, alignment_score, unmapped_elements
    """
    module_name = extract_module_name(rtl_code) or "top"

    # Extract RTL signals
    rtl_inputs = set(re.findall(r'input\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code))
    rtl_outputs = set(re.findall(r'output\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code))
    rtl_wires = set(re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code))
    rtl_regs = set(re.findall(r'reg\s+(?:\[\d+:\d+\])?\s*(\w+)', rtl_code))

    all_rtl_signals = rtl_inputs | rtl_outputs | rtl_wires | rtl_regs

    # If no netlist provided, synthesize to get one
    if netlist_code is None:
        temp_file = write_temp_verilog(rtl_code)
        temp_netlist = temp_file.replace(".v", "_netlist.v")

        try:
            yosys_script = f"""
read_verilog -I{TOOLS_ROOT}/incdir {temp_file}
hierarchy -top {module_name}
proc; opt; techmap
abc -g gates
write_verilog {temp_netlist}
            """
            yosys_cmd = f"yosys -p '{yosys_script}' 2>&1"
            returncode, stdout, stderr = run_with_conda(yosys_cmd, timeout=YOSYS_TIMEOUT)

            if returncode == 0 and os.path.exists(temp_netlist):
                with open(temp_netlist, 'r') as f:
                    netlist_code = f.read()
            else:
                netlist_code = ""
        finally:
            for f in [temp_file, temp_netlist]:
                if os.path.exists(f):
                    os.remove(f)

    if not netlist_code:
        # synthesis produced no netlist: there is nothing to map against
        return asdict(CrossStageResult(
            status="error", rtl_to_netlist_mapping={}, alignment_score=0.0, unmapped_elements=[],
            mapping_statistics={'rtl_signals': len(all_rtl_signals)},
            error="Synthesis did not produce a netlist"))

    # Extract netlist signals
    netlist_wires = set(re.findall(r'wire\s+(?:\[\d+:\d+\])?\s*(\w+)', netlist_code)) if netlist_code else set()
    netlist_cells = re.findall(r'(\$\w+)\s+\w+\s*\(', netlist_code) if netlist_code else []

    # Build mapping
    mapping = {}
    mapped_count = 0

    for rtl_sig in all_rtl_signals:
        # Find matching netlist signals (exact or partial match)
        matches = []
        for net_sig in netlist_wires:
            if rtl_sig in net_sig or net_sig.startswith(rtl_sig):
                matches.append(net_sig)

        if matches:
            mapping[rtl_sig] = matches[:5]  # Limit matches
            mapped_count += 1
        else:
            mapping[rtl_sig] = []

    # Calculate alignment score
    total_signals = len(all_rtl_signals)
    alignment_score = (mapped_count / total_signals * 100) if total_signals > 0 else 0.0

    # Find unmapped elements
    unmapped = [sig for sig, matches in mapping.items() if not matches]

    return asdict(CrossStageResult(
        status="success",
        rtl_to_netlist_mapping=mapping,
        alignment_score=round(alignment_score, 2),
        unmapped_elements=unmapped[:20],
        mapping_statistics={
            'rtl_signals': len(all_rtl_signals),
            'netlist_wires': len(netlist_wires),
            'netlist_cells': len(set(netlist_cells)),
            'mapped_signals': mapped_count,
            'unmapped_signals': len(unmapped)
        }
    ))


# ============================================================================
# Tool Registry and Dispatcher
# ============================================================================

TOOL_REGISTRY = {
    'synthesis_tool': synthesis_tool,
    'simulation_tool': simulation_tool,
    'graph_extractor': graph_extractor,
    'static_analyzer': static_analyzer,
    'optimization_advisor': optimization_advisor,
    'cross_stage_mapper': cross_stage_mapper
}


def execute_tool(tool_name: str, verilog_code: str, **kwargs) -> Dict[str, Any]:
    """
    Execute a tool by name with the given parameters.

    Args:
        tool_name: Name of the tool to execute
        verilog_code: Verilog source code
        **kwargs: Additional tool-specific parameters

    Returns:
        Tool result as a dictionary
    """
    if tool_name not in TOOL_REGISTRY:
        return {'status': 'error', 'error': f'Unknown tool: {tool_name}'}

    tool_func = TOOL_REGISTRY[tool_name]

    try:
        if tool_name == 'cross_stage_mapper':
            return tool_func(verilog_code, kwargs.get('netlist_code'))
        else:
            return tool_func(verilog_code, **kwargs)
    except Exception as e:
        return {'status': 'error', 'error': str(e)}


# ============================================================================
# Test Function
# ============================================================================

def test_all_tools():
    """Test all tools with a simple Verilog module."""
    test_code = """
module counter(
    input clk,
    input rst,
    input enable,
    output reg [7:0] count
);
    always @(posedge clk or posedge rst) begin
        if (rst)
            count <= 8'b0;
        else if (enable)
            count <= count + 1;
    end
endmodule
"""

    print("=" * 60)
    print("Testing EDA Tool Suite")
    print("=" * 60)

    for tool_name in TOOL_REGISTRY:
        print(f"\n--- Testing {tool_name} ---")
        try:
            result = execute_tool(tool_name, test_code)
            print(f"Status: {result.get('status', 'unknown')}")
            if result.get('status') == 'error':
                print(f"Error: {result.get('error', 'unknown')}")
            else:
                # Print key metrics
                for key in ['gate_count', 'node_count', 'alignment_score', 'module_name']:
                    if key in result:
                        print(f"  {key}: {result[key]}")
        except Exception as e:
            print(f"Exception: {e}")

    print("\n" + "=" * 60)
    print("Tool Suite Test Complete")
    print("=" * 60)


if __name__ == "__main__":
    test_all_tools()