File size: 31,084 Bytes
676defa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
CircuitQA-Tool V7 Dataset Generator

Generates the question-answer corpus with:
- All 6 tools: synthesis_tool, simulation_tool, graph_extractor,
               static_analyzer, optimization_advisor, cross_stage_mapper
- All 6 question categories with balanced distribution (~16.7% each)
- Backend outputs from Yosys and Icarus Verilog (see eda_tools.py)
- Two-stage training support (Stage 1: tool selection, Stage 2: answer generation)

Input: Verilog files from CircuitQA_datasets
Output: V7 JSONL with full CircuitQA-Tool structure
"""

import os
import sys
import json
import random
import hashlib
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass, asdict, field
from collections import defaultdict
import argparse
import re
from concurrent.futures import ProcessPoolExecutor, as_completed
import traceback
import subprocess

# Get conda path from environment or use default
CONDA_PATH = os.environ.get('CONDA_PREFIX', os.path.expanduser("~/miniconda3"))

def check_eda_dependencies():
    """Verify EDA tools are available in conda 'eda' environment."""
    try:
        # Check Yosys
        result = subprocess.run(
            f"source {CONDA_PATH}/bin/activate eda && yosys -V",
            shell=True, capture_output=True, text=True, timeout=10
        )
        if result.returncode != 0:
            print("WARNING: Yosys not found in conda 'eda' environment", flush=True)
            return False
        print(f"✓ Yosys available: {result.stdout.strip()}", flush=True)

        # Check iverilog
        result = subprocess.run(
            f"source {CONDA_PATH}/bin/activate eda && iverilog -V",
            shell=True, capture_output=True, text=True, timeout=10
        )
        if result.returncode != 0:
            print("WARNING: Icarus Verilog not found", flush=True)
        else:
            print(f"✓ Icarus Verilog available", flush=True)

        return True
    except Exception as e:
        print(f"WARNING: Failed to check EDA dependencies: {e}", flush=True)
        return False

# Add processing directory to path
sys.path.insert(0, os.path.dirname(__file__))
from eda_tools import (
    synthesis_tool, simulation_tool, graph_extractor,
    static_analyzer, optimization_advisor, cross_stage_mapper,
    TOOL_REGISTRY, extract_module_name
)

# ============================================================================
# Question Templates by Category
# ============================================================================

QUESTION_TEMPLATES = {
    # Category 1: Design Quality Prediction (PPA Metrics)
    "design_quality": [
        ("What is the estimated area of module {module}?", "area"),
        ("What is the estimated delay of module {module}?", "delay"),
        ("What is the estimated power consumption of module {module}?", "power"),
        ("How many gates are in module {module} after synthesis?", "gate_count"),
        ("What is the critical path delay of module {module}?", "critical_path"),
        ("Compare the area and delay trade-offs for module {module}.", "ppa_tradeoff"),
    ],

    # Category 2: Functional Behavior & Assertions
    "functional_behavior": [
        ("What is the toggle rate of signal {signal} in module {module}?", "toggle_rate"),
        ("How many simulation cycles does module {module} require for coverage?", "coverage"),
        ("What is the signal activity profile of module {module}?", "activity"),
        ("Describe the functional behavior of module {module}.", "behavior"),
        ("What are the input/output relationships in module {module}?", "io_relation"),
    ],

    # Category 3: Structural Analysis
    "structural_analysis": [
        ("How many nodes are in the {graph_type} graph of module {module}?", "node_count"),
        ("What is the average degree of nodes in module {module}'s graph?", "avg_degree"),
        ("Describe the graph structure of module {module}.", "graph_structure"),
        ("What are the main cell types in module {module}?", "cell_types"),
        ("How many edges connect the nodes in module {module}'s {graph_type}?", "edge_count"),
    ],

    # Category 4: Code Understanding & Explanation
    "code_understanding": [
        ("Explain what module {module} does.", "explanation"),
        ("How many inputs and outputs does module {module} have?", "port_count"),
        ("What is the complexity of module {module}?", "complexity"),
        ("Describe the always blocks in module {module}.", "always_blocks"),
        ("What signals are defined in module {module}?", "signals"),
        ("Are there any potential issues in module {module}?", "lint"),
    ],

    # Category 5: Design Optimization & Recommendations
    "optimization": [
        ("What synthesis optimizations should be applied to module {module} for {target}?", "recipe"),
        ("How can I reduce the area of module {module}?", "area_opt"),
        ("How can I improve the timing of module {module}?", "delay_opt"),
        ("How can I reduce power consumption in module {module}?", "power_opt"),
        ("What are the trade-offs of optimizing module {module} for {target}?", "tradeoffs"),
    ],

    # Category 6: Cross-Stage Reasoning
    "cross_stage": [
        ("How does module {module} map from RTL to netlist?", "mapping"),
        ("What is the alignment score between RTL and netlist for module {module}?", "alignment"),
        ("Which RTL signals are unmapped in the netlist for module {module}?", "unmapped"),
        ("How many netlist cells correspond to module {module}?", "netlist_cells"),
    ],
}

# Tool mapping for each category
CATEGORY_TOOLS = {
    "design_quality": "synthesis_tool",
    "functional_behavior": "simulation_tool",
    "structural_analysis": "graph_extractor",
    "code_understanding": "static_analyzer",
    "optimization": "optimization_advisor",
    "cross_stage": "cross_stage_mapper",
}

# ============================================================================
# V7 Data Structures
# ============================================================================

@dataclass
class V7QAPair:
    """V7 QA pair with full tool-calling support for all 6 categories."""
    # Core QA fields
    question: str
    answer: str

    # Verilog context
    source_file: str
    module_name: str
    verilog_code: str

    # Tool calling
    tool_name: str
    tool_parameters: Dict[str, Any]
    tool_result: Dict[str, Any]

    # Metadata
    category: str
    subcategory: str
    difficulty: str
    question_hash: str = ""

    # Two-stage training
    stage1_target: str = ""
    stage2_context: str = ""

    def __post_init__(self):
        if not self.question_hash:
            self.question_hash = hashlib.md5(
                f"{self.question}{self.module_name}".encode()
            ).hexdigest()[:12]


# ============================================================================
# Answer Generation Functions
# ============================================================================

def generate_design_quality_answer(question: str, subcategory: str,
                                   tool_result: Dict, module_name: str) -> str:
    """Generate answer for design quality questions."""
    if tool_result.get('status') != 'success':
        return f"Unable to analyze module {module_name}: {tool_result.get('error', 'unknown error')}"

    if subcategory == "area":
        area = tool_result.get('area', 0)
        return f"The estimated area of module {module_name} is {area:.2f} area units. This is based on synthesis with {tool_result.get('gate_count', 0)} gates."

    elif subcategory == "delay":
        delay = tool_result.get('delay', 0)
        return f"The estimated delay of module {module_name} is {delay:.2f} ps. The critical path estimate is {tool_result.get('critical_path_estimate', 0):.2f} ps."

    elif subcategory == "power":
        power = tool_result.get('power', 0)
        return f"The estimated power consumption of module {module_name} is {power:.4f} mW, based on {tool_result.get('gate_count', 0)} gates."

    elif subcategory == "gate_count":
        gate_count = tool_result.get('gate_count', 0)
        breakdown = tool_result.get('cell_breakdown', {})
        breakdown_str = ", ".join(f"{k}: {v}" for k, v in list(breakdown.items())[:5])
        return f"Module {module_name} synthesizes to {gate_count} gates. Cell breakdown: {breakdown_str}."

    elif subcategory == "critical_path":
        cp = tool_result.get('critical_path_estimate', 0)
        return f"The critical path delay of module {module_name} is approximately {cp:.2f} ps."

    else:  # ppa_tradeoff
        return f"Module {module_name} has area={tool_result.get('area', 0):.2f}, delay={tool_result.get('delay', 0):.2f}ps, power={tool_result.get('power', 0):.4f}mW. Trade-off: reducing area may increase delay."


def generate_functional_behavior_answer(question: str, subcategory: str,
                                        tool_result: Dict, module_name: str,
                                        signal_name: str = None) -> str:
    """Generate answer for functional behavior questions."""
    if tool_result.get('status') not in ['success', 'estimated']:
        return f"Unable to simulate module {module_name}: {tool_result.get('error', 'unknown error')}"

    if subcategory == "toggle_rate" and signal_name:
        toggle_rates = tool_result.get('toggle_rates', {})
        rate = toggle_rates.get(signal_name, 0.0)
        return f"The toggle rate of signal {signal_name} in module {module_name} is {rate:.3f} (toggles per cycle)."

    elif subcategory == "coverage":
        cycles = tool_result.get('simulation_cycles', 0)
        coverage = tool_result.get('coverage_estimate', 0)
        return f"Module {module_name} requires approximately {cycles} simulation cycles for {coverage:.1f}% coverage."

    elif subcategory == "activity":
        activity = tool_result.get('signal_activity', {})
        return f"Module {module_name} has {activity.get('inputs', 0)} inputs, {activity.get('outputs', 0)} outputs, {activity.get('wires', 0)} wires, and {activity.get('regs', 0)} registers."

    else:  # behavior, io_relation
        activity = tool_result.get('signal_activity', {})
        return f"Module {module_name} processes {activity.get('inputs', 0)} inputs to produce {activity.get('outputs', 0)} outputs through {activity.get('regs', 0)} sequential elements."


def generate_structural_analysis_answer(question: str, subcategory: str,
                                        tool_result: Dict, module_name: str,
                                        graph_type: str = "CDFG") -> str:
    """Generate answer for structural analysis questions."""
    if tool_result.get('status') != 'success':
        return f"Unable to extract graph for module {module_name}: {tool_result.get('error', 'unknown error')}"

    if subcategory == "node_count":
        count = tool_result.get('node_count', 0)
        return f"The {graph_type} graph of module {module_name} contains {count} nodes."

    elif subcategory == "edge_count":
        count = tool_result.get('edge_count', 0)
        return f"The {graph_type} graph of module {module_name} contains {count} edges connecting the nodes."

    elif subcategory == "avg_degree":
        props = tool_result.get('graph_properties', {})
        avg_deg = props.get('avg_degree', 0)
        return f"The average node degree in module {module_name}'s graph is {avg_deg:.2f}."

    elif subcategory == "cell_types":
        props = tool_result.get('graph_properties', {})
        types = props.get('node_types', {})
        types_str = ", ".join(f"{k}: {v}" for k, v in list(types.items())[:5])
        return f"Module {module_name} contains the following cell types: {types_str}."

    else:  # graph_structure
        return f"Module {module_name}'s {graph_type} has {tool_result.get('node_count', 0)} nodes and {tool_result.get('edge_count', 0)} edges with average degree {tool_result.get('graph_properties', {}).get('avg_degree', 0):.2f}."


def generate_code_understanding_answer(question: str, subcategory: str,
                                       tool_result: Dict, module_name: str) -> str:
    """Generate answer for code understanding questions."""
    if tool_result.get('status') != 'success':
        return f"Unable to analyze module {module_name}: {tool_result.get('error', 'unknown error')}"

    if subcategory == "explanation":
        ports = tool_result.get('port_count', {})
        complexity = tool_result.get('code_complexity', {})
        return f"Module {module_name} is a Verilog module with {ports.get('inputs', 0)} inputs and {ports.get('outputs', 0)} outputs. It has {tool_result.get('always_blocks', 0)} always blocks and {tool_result.get('assign_statements', 0)} assign statements."

    elif subcategory == "port_count":
        ports = tool_result.get('port_count', {})
        return f"Module {module_name} has {ports.get('inputs', 0)} inputs, {ports.get('outputs', 0)} outputs, and {ports.get('inouts', 0)} bidirectional ports (total: {ports.get('total', 0)})."

    elif subcategory == "complexity":
        complexity = tool_result.get('code_complexity', {})
        return f"Module {module_name} has cyclomatic complexity of {complexity.get('cyclomatic_complexity', 0)}, {complexity.get('lines_of_code', 0)} lines of code, and nesting depth of {complexity.get('nesting_depth', 0)}."

    elif subcategory == "always_blocks":
        count = tool_result.get('always_blocks', 0)
        return f"Module {module_name} contains {count} always blocks for sequential and combinational logic."

    elif subcategory == "signals":
        signals = tool_result.get('signal_count', {})
        return f"Module {module_name} defines {signals.get('wires', 0)} wires, {signals.get('regs', 0)} registers, and {signals.get('parameters', 0)} parameters."

    else:  # lint
        warnings = tool_result.get('lint_warnings', [])
        if warnings:
            return f"Potential issues in module {module_name}: {'; '.join(warnings[:3])}."
        return f"No obvious issues detected in module {module_name}."


def generate_optimization_answer(question: str, subcategory: str,
                                 tool_result: Dict, module_name: str,
                                 target: str = "area") -> str:
    """Generate answer for optimization questions."""
    if tool_result.get('status') != 'success':
        return f"Unable to analyze module {module_name}: {tool_result.get('error', 'unknown error')}"

    recipes = tool_result.get('recommended_recipes', [])
    suggestions = tool_result.get('optimization_suggestions', [])
    improvement = tool_result.get('estimated_improvement', {})
    trade_offs = tool_result.get('trade_offs', [])

    if subcategory == "recipe":
        recipe_str = "; ".join(recipes[:2]) if recipes else "default synthesis"
        return f"For {target} optimization of module {module_name}, apply: {recipe_str}"

    elif subcategory in ["area_opt", "delay_opt", "power_opt"]:
        if suggestions:
            sugg_str = "; ".join(s.get('description', '') for s in suggestions[:2])
            return f"To optimize {module_name}: {sugg_str}"
        return f"Apply standard {target} optimization to module {module_name}."

    else:  # tradeoffs
        if trade_offs:
            return f"Trade-offs for optimizing {module_name} for {target}: {'; '.join(trade_offs[:2])}"
        return f"Optimizing {module_name} for {target} may affect other metrics."


def generate_cross_stage_answer(question: str, subcategory: str,
                                tool_result: Dict, module_name: str) -> str:
    """Generate answer for cross-stage reasoning questions."""
    if tool_result.get('status') != 'success':
        return f"Unable to map module {module_name}: {tool_result.get('error', 'unknown error')}"

    stats = tool_result.get('mapping_statistics', {})

    if subcategory == "mapping":
        return f"Module {module_name} maps {stats.get('rtl_signals', 0)} RTL signals to {stats.get('netlist_wires', 0)} netlist wires through {stats.get('netlist_cells', 0)} cells."

    elif subcategory == "alignment":
        score = tool_result.get('alignment_score', 0)
        return f"The RTL-to-netlist alignment score for module {module_name} is {score:.1f}%."

    elif subcategory == "unmapped":
        unmapped = tool_result.get('unmapped_elements', [])
        if unmapped:
            return f"Unmapped RTL signals in module {module_name}: {', '.join(unmapped[:5])}."
        return f"All RTL signals in module {module_name} are mapped to the netlist."

    else:  # netlist_cells
        return f"Module {module_name} synthesizes to {stats.get('netlist_cells', 0)} netlist cells."




# ============================================================================
# V7 Generator Class
# ============================================================================

class V7Generator:
    """Generate V7 dataset with all 6 tools and 6 categories."""

    def __init__(self, base_dir: str, output_file: str):
        self.base_dir = Path(base_dir)
        self.output_file = Path(output_file)

        # Statistics
        self.stats = defaultdict(int)
        self.category_counts = defaultdict(int)
        self.tool_counts = defaultdict(int)

        # Cache for tool results
        self.tool_cache: Dict[str, Dict] = {}

    def find_verilog_files(self) -> List[Path]:
        """Find all Verilog files in the base directory."""
        verilog_files = []
        for ext in ['*.v', '*.sv']:
            verilog_files.extend(self.base_dir.rglob(ext))
        return verilog_files

    def read_verilog_file(self, filepath: Path) -> Tuple[str, str]:
        """Read Verilog file and extract module name."""
        try:
            with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                content = f.read()
            module_name = extract_module_name(content)
            return content, module_name or filepath.stem
        except Exception as e:
            return "", ""

    def get_tool_result(self, tool_name: str, verilog_code: str,
                        **kwargs) -> Dict[str, Any]:
        """Get tool result with caching."""
        # Use longer hash (16 chars = 64 bits) to reduce collision probability
        cache_key = f"{tool_name}:{hashlib.md5(verilog_code.encode()).hexdigest()[:16]}"

        if cache_key in self.tool_cache:
            return self.tool_cache[cache_key]

        tool_func = TOOL_REGISTRY.get(tool_name)
        if not tool_func:
            return {'status': 'error', 'error': f'Unknown tool: {tool_name}'}

        try:
            if tool_name == 'cross_stage_mapper':
                result = tool_func(verilog_code, None)
            elif tool_name == 'graph_extractor':
                result = tool_func(verilog_code, kwargs.get('graph_type', 'CDFG'))
            elif tool_name == 'optimization_advisor':
                result = tool_func(verilog_code, kwargs.get('target_metric', 'area'))
            elif tool_name == 'simulation_tool':
                result = tool_func(verilog_code, kwargs.get('num_cycles', 100))
            elif tool_name == 'synthesis_tool':
                result = tool_func(verilog_code, kwargs.get('optimization_level', 'medium'))
            else:
                result = tool_func(verilog_code)

            self.tool_cache[cache_key] = result
            return result
        except Exception as e:
            return {'status': 'error', 'error': str(e)}

    def generate_qa_for_module(self, verilog_code: str, module_name: str,
                               source_file: str) -> List[Dict]:
        """Generate QA pairs for a single module across all categories."""
        qa_pairs = []

        # Get signals for functional behavior questions
        signals = re.findall(r'(?:input|output|wire|reg)\s+(?:\[\d+:\d+\])?\s*(\w+)',
                            verilog_code)
        signals = list(set(signals))[:5]  # Limit to 5 signals

        graph_types = ['CDFG', 'AIG', 'DFG']
        targets = ['area', 'delay', 'power']

        # Target 2 QA pairs per category for balanced distribution
        target_per_category = 2

        for category in QUESTION_TEMPLATES.keys():
            tool_name = CATEGORY_TOOLS[category]
            templates = list(QUESTION_TEMPLATES[category])
            random.shuffle(templates)

            category_pairs_generated = 0

            for template, subcategory in templates:
                # Stop once we have enough pairs for this category
                if category_pairs_generated >= target_per_category:
                    break

                try:
                    # Skip signal-based questions if no signals found
                    if '{signal}' in template and not signals:
                        continue

                    # Format question
                    signal = None
                    graph_type = 'CDFG'
                    target = 'area'

                    if '{signal}' in template:
                        signal = random.choice(signals)
                        question = template.format(module=module_name, signal=signal)
                    elif '{graph_type}' in template:
                        graph_type = random.choice(graph_types)
                        question = template.format(module=module_name, graph_type=graph_type)
                    elif '{target}' in template:
                        target = random.choice(targets)
                        question = template.format(module=module_name, target=target)
                    else:
                        question = template.format(module=module_name)

                    # Get tool parameters
                    tool_params = self._get_tool_params(tool_name, graph_type, target)

                    # Execute tool
                    tool_result = self.get_tool_result(tool_name, verilog_code, **tool_params)

                    # Generate answer
                    answer = self._generate_answer(category, subcategory, question,
                                                   tool_result, module_name,
                                                   signal, graph_type, target)

                    # Create stage1 target (tool call JSON)
                    stage1_target = json.dumps({
                        'tool': tool_name,
                        'parameters': tool_params
                    })

                    # Create improved stage2 context (keep essential fields, truncate logs)
                    essential_result = {k: v for k, v in tool_result.items()
                                       if k not in ['synthesis_log', 'simulation_log', 'nodes', 'edges']}
                    stage2_context = f"Question: {question}\n\nTool: {tool_name}\nResult: {json.dumps(essential_result)}"
                    if len(stage2_context) > 1500:
                        stage2_context = stage2_context[:1500] + "..."

                    # Determine difficulty (easy/medium)
                    difficulty = self._estimate_difficulty(subcategory, tool_result)

                    qa_pair = {
                        'question': question,
                        'answer': answer,
                        'source_file': source_file,
                        'module_name': module_name,
                        'verilog_code': verilog_code[:3000],  # Limit code size
                        'tool_name': tool_name,
                        'tool_parameters': tool_params,
                        'tool_result': tool_result,
                        'category': category,
                        'subcategory': subcategory,
                        'difficulty': difficulty,
                        'question_hash': hashlib.md5(f"{question}{module_name}".encode()).hexdigest()[:12],
                        'stage1_target': stage1_target,
                        'stage2_context': stage2_context
                    }

                    qa_pairs.append(qa_pair)
                    self.category_counts[category] += 1
                    self.tool_counts[tool_name] += 1
                    category_pairs_generated += 1

                except Exception as e:
                    self.stats['errors'] += 1
                    continue

        return qa_pairs


    def _get_tool_params(self, tool_name: str,
                         graph_type: str = 'CDFG', target: str = 'area') -> Dict:
        """Get tool parameters based on tool name."""
        if tool_name == 'synthesis_tool':
            return {'optimization_level': 'medium'}
        elif tool_name == 'simulation_tool':
            return {'num_cycles': 100, 'simulation_type': 'functional'}
        elif tool_name == 'graph_extractor':
            return {'graph_type': graph_type}
        elif tool_name == 'static_analyzer':
            return {'analysis_type': 'full'}
        elif tool_name == 'optimization_advisor':
            return {'target_metric': target}
        elif tool_name == 'cross_stage_mapper':
            return {}
        return {}

    def _generate_answer(self, category: str, subcategory: str, question: str,
                         tool_result: Dict, module_name: str, signal: str = None,
                         graph_type: str = 'CDFG', target: str = 'area') -> str:
        """Generate answer based on category."""
        if category == 'design_quality':
            return generate_design_quality_answer(question, subcategory, tool_result, module_name)
        elif category == 'functional_behavior':
            return generate_functional_behavior_answer(question, subcategory, tool_result, module_name, signal)
        elif category == 'structural_analysis':
            return generate_structural_analysis_answer(question, subcategory, tool_result, module_name, graph_type)
        elif category == 'code_understanding':
            return generate_code_understanding_answer(question, subcategory, tool_result, module_name)
        elif category == 'optimization':
            return generate_optimization_answer(question, subcategory, tool_result, module_name, target)
        elif category == 'cross_stage':
            return generate_cross_stage_answer(question, subcategory, tool_result, module_name)
        return f"Analysis of module {module_name} completed."

    def _estimate_difficulty(self, subcategory: str, tool_result: Dict) -> str:
        """Estimate question difficulty (easy or medium)."""
        if tool_result.get('status') == 'error':
            return 'medium'

        # Simple heuristics
        if subcategory in ['port_count', 'gate_count', 'node_count', 'alignment']:
            return 'easy'
        return 'medium'

    def generate(self, max_files: int = None, target_pairs: int = 100000):
        """Generate V7 dataset."""
        import sys
        print(f"Finding Verilog files in {self.base_dir}...", flush=True)
        verilog_files = self.find_verilog_files()
        print(f"Found {len(verilog_files)} Verilog files", flush=True)

        if max_files:
            verilog_files = verilog_files[:max_files]

        all_qa_pairs = []

        with open(self.output_file, 'w') as f:
            for i, filepath in enumerate(verilog_files):
                if len(all_qa_pairs) >= target_pairs:
                    print(f"Reached target of {target_pairs} pairs", flush=True)
                    break

                try:
                    verilog_code, module_name = self.read_verilog_file(filepath)
                    if not verilog_code or not module_name:
                        self.stats['skipped'] += 1
                        continue

                    # Skip very small or very large files
                    if len(verilog_code) < 50 or len(verilog_code) > 50000:
                        self.stats['skipped'] += 1
                        continue

                    source_file = str(filepath.relative_to(self.base_dir))
                    qa_pairs = self.generate_qa_for_module(verilog_code, module_name, source_file)

                    for qa in qa_pairs:
                        f.write(json.dumps(qa) + '\n')
                        all_qa_pairs.append(qa)
                    f.flush()  # Flush after each module

                    self.stats['files_processed'] += 1

                    if (i + 1) % 50 == 0:
                        print(f"Processed {i+1}/{len(verilog_files)} files, {len(all_qa_pairs)} QA pairs", flush=True)
                        sys.stdout.flush()

                except Exception as e:
                    self.stats['errors'] += 1
                    continue

        self.stats['total_pairs'] = len(all_qa_pairs)
        return all_qa_pairs

    def print_stats(self):
        """Print generation statistics."""
        print("\n" + "=" * 60)
        print("V7 Dataset Generation Statistics")
        print("=" * 60)
        print(f"Files processed: {self.stats['files_processed']}")
        print(f"Files skipped: {self.stats['skipped']}")
        print(f"Errors: {self.stats['errors']}")
        print(f"Total QA pairs: {self.stats['total_pairs']}")

        print("\nCategory Distribution:")
        total = sum(self.category_counts.values())
        for cat, count in sorted(self.category_counts.items()):
            pct = count / total * 100 if total > 0 else 0
            print(f"  {cat}: {count} ({pct:.1f}%)")

        print("\nTool Usage:")
        for tool, count in sorted(self.tool_counts.items()):
            pct = count / total * 100 if total > 0 else 0
            print(f"  {tool}: {count} ({pct:.1f}%)")


# ============================================================================
# Main Function
# ============================================================================

def main():
    parser = argparse.ArgumentParser(description='Generate V7 CircuitQA-Tool dataset')
    parser.add_argument('--base-dir', type=str, default='.',
                        help='Base directory containing Verilog files')
    parser.add_argument('--output', type=str, default='v7_qa_dataset.jsonl',
                        help='Output JSONL file')
    parser.add_argument('--max-files', type=int, default=None,
                        help='Maximum number of files to process')
    parser.add_argument('--target-pairs', type=int, default=100000,
                        help='Target number of QA pairs')
    parser.add_argument('--skip-eda-check', action='store_true',
                        help='Skip EDA tool dependency check')

    args = parser.parse_args()

    # Check EDA dependencies
    if not args.skip_eda_check:
        print("Checking EDA tool dependencies...", flush=True)
        if not check_eda_dependencies():
            print("WARNING: Some EDA tools missing. Results may be estimated.", flush=True)
        print("", flush=True)

    generator = V7Generator(args.base_dir, args.output)
    generator.generate(max_files=args.max_files, target_pairs=args.target_pairs)
    generator.print_stats()


if __name__ == '__main__':
    main()