Spaces:
Runtime error

File size: 25,049 Bytes
ce06eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
文件生成器模块 - 生成指标方案的多种格式文件 (v3.0)

本模块负责将指标建模结果生成多种格式的输出文件,支持批量生成和单个生成。
适用于数据指标建模助手 v3.0 版本。

主要功能:
1. 生成 Markdown 文档(指标说明文档)
2. 生成 SQL 查询语句文件
3. 生成 JSON 格式的表结构定义
4. 支持批量生成(多个指标)
5. 支持 BI 设计文档输出
6. 生成合并文件(所有指标整合到一个文件)

更新日志 (v3.0):
- 输入参数改为 IndicatorSet + schemes(来自 ModelingAgent)
- 支持批量文件生成(多个指标同时生成)
- 支持 BI 设计输出(可选)

依赖:
- models.indicator.Indicator: 指标数据模型
- models.indicator_set.IndicatorSet: 指标集数据模型
- config.settings.OUTPUT_DIR: 输出目录配置

作者: 数据指标建模助手开发团队
版本: 3.0
"""

import json
import os
from pathlib import Path
from datetime import datetime
import logging
from typing import Dict, Any, List, Optional

# 导入数据模型
from models.indicator import Indicator
from models.indicator_set import IndicatorSet


# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class FileGenerator:
    """
    文件生成器类 - 生成指标方案的输出文件
    
    负责将指标集和建模方案生成多种格式的文件,
    包括 Markdown 文档、SQL 文件、JSON 文件等。
    支持单个指标和批量指标的文件生成。
    
    属性:
        output_dir (Path): 输出文件目录路径
        logger (Logger): 日志记录器
        
    主要功能:
        - 生成单个指标的文件(.md, .sql, .json)
        - 生成指标集的合并文件
        - 生成 BI 设计文档
        - 批量生成多个指标的文件
    """
    
    def __init__(self, output_dir: Optional[str] = None):
        """
        初始化文件生成器
        
        参数:
            output_dir (Optional[str]): 输出文件目录路径
                如果为 None,则使用配置文件中的 OUTPUT_DIR
                
        返回:
            None
            
        示例:
            >>> generator = FileGenerator()  # 使用默认输出目录
            >>> generator = FileGenerator("/path/to/output")  # 指定输出目录
        """
        if output_dir is None:
            # 使用默认输出目录(从配置文件读取)
            from config.settings import OUTPUT_DIR
            self.output_dir = OUTPUT_DIR
        else:
            # 使用指定的输出目录
            self.output_dir = Path(output_dir)
        
        # 创建输出目录(如果不存在)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        logger.info(f"FileGenerator 初始化完成,输出目录: {self.output_dir}")
    
    def generate_all(
        self,
        indicator_set: IndicatorSet,
        schemes: List[Dict[str, Any]],
        bi_design: Optional[Dict[str, Any]] = None
    ) -> Dict[str, str]:
        """
        为指标集和所有方案生成完整的输出文件
        
        核心方法:批量生成指标集的所有相关文件,
        包括单个指标文件和合并文件。
        
        参数:
            indicator_set (IndicatorSet): 指标集对象,包含多个指标定义
            schemes (List[Dict]): 建模方案列表,来自 ModelingAgent 的输出
                每个方案包含:indicator_id, indicator_name, markdown, sql, table_structure
            bi_design (Optional[Dict]): BI 设计方案,来自 BIDesignAgent(可选)
                包含:markdown, charts, dashboard_layout 等
            
        返回:
            Dict[str, str]: 生成的文件路径字典,结构如下:
            {
                "indicator_set": str,      # 指标集合并 JSON 文件路径
                "markdown": str,           # 合并 Markdown 文件路径
                "sql": str,                # 合并 SQL 文件路径
                "bi_design": str,          # BI 设计 Markdown 文件路径(可选)
                "files": [                 # 每个指标的独立文件列表
                    {
                        "indicator_id": str,
                        "indicator_name": str,
                        "markdown": str,
                        "sql": str,
                        "json": str
                    }
                ]
            }
            
        处理流程:
            1. 遍历所有方案,为每个指标生成独立文件
            2. 生成指标集的合并 JSON 文件
            3. 生成所有指标的合并 Markdown 文件
            4. 生成所有指标的合并 SQL 文件
            5. 如果提供 BI 设计,生成 BI 设计文档
        """
        logger.info(f"开始为指标集生成所有文件: {indicator_set.set_name}")
        
        # 初始化返回结果字典
        files = {
            "indicator_set": "",
            "markdown": "",
            "sql": "",
            "files": []
        }
        
        # 1. 为每个方案生成独立文件
        for scheme in schemes:
            ind_id = scheme.get("indicator_id")
            ind_name = scheme.get("indicator_name", "unknown")
            
            # 在指标集中查找对应的指标对象
            indicator = indicator_set.get_indicator(ind_id)
            
            # 为该指标生成文件(Markdown, SQL, JSON)
            generated = self._generate_for_indicator(
                indicator=indicator,
                scheme=scheme,
                indicator_set=indicator_set
            )
            
            # 将生成的文件信息添加到列表
            files["files"].append(generated)
        
        # 2. 生成合并文件(所有指标整合到一个文件)
        files["indicator_set"] = self._generate_indicator_set_json(indicator_set, schemes)
        files["markdown"] = self._generate_combined_markdown(indicator_set, schemes)
        files["sql"] = self._generate_combined_sql(schemes)
        
        # 3. 生成 BI 设计文件(如果提供)
        if bi_design:
            files["bi_design"] = self._generate_bi_design_markdown(bi_design, indicator_set)
        
        logger.info(f"文件生成完成,共生成 {len(files['files'])} 个指标文件 + 合并文件")
        
        return files
    
    def generate_indicator_set(
        self,
        indicator_set: IndicatorSet
    ) -> Dict[str, str]:
        """
        仅生成指标集的定义文件(不包含方案)
        
        当需要仅输出指标集定义(还没有 SQL/表结构)时使用。
        
        参数:
            indicator_set (IndicatorSet): 指标集对象
            
        返回:
            Dict[str, str]: 文件路径字典
            {
                "indicator_set_json": str,    # 指标集 JSON 文件路径
                "indicator_set_markdown": str  # 指标集 Markdown 文件路径
            }
        """
        logger.info(f"生成指标集文件: {indicator_set.set_name}")
        
        # 生成指标集 JSON 文件
        json_path = self._save_indicator_set_json(indicator_set)
        
        # 生成指标集 Markdown 文件
        md_path = self._save_indicator_set_markdown(indicator_set)
        
        return {
            "indicator_set_json": json_path,
            "indicator_set_markdown": md_path
        }
    
    def generate_bi_design(
        self,
        bi_design: Dict[str, Any],
        indicator_set: IndicatorSet
    ) -> Dict[str, str]:
        """
        生成 BI 设计文件
        
        参数:
            bi_design (Dict[str, Any]): BI 设计方案,来自 BIDesignAgent
            indicator_set (IndicatorSet): 指标集对象(用于上下文)
            
        返回:
            Dict[str, str]: 文件路径字典
            {
                "bi_design_markdown": str  # BI 设计 Markdown 文件路径
            }
        """
        logger.info(f"生成 BI 设计文件: {indicator_set.set_name}")
        
        # 生成 BI 设计 Markdown 文件
        md_path = self._generate_bi_design_markdown(bi_design, indicator_set)
        
        return {
            "bi_design_markdown": md_path
        }
    
    def _generate_for_indicator(
        self,
        indicator: Optional[Indicator],
        scheme: Dict[str, Any],
        indicator_set: IndicatorSet
    ) -> Dict[str, str]:
        """
        为单个指标生成输出文件
        
        内部方法:根据方案内容生成该指标的 Markdown、SQL、JSON 文件。
        
        参数:
            indicator (Optional[Indicator]): 指标对象(如果找不到可以为 None)
            scheme (Dict[str, Any]): 该指标的建模方案
            indicator_set (IndicatorSet): 父指标集(用于上下文)
            
        返回:
            Dict[str, str]: 该指标的文件路径字典
            {
                "indicator_id": str,
                "indicator_name": str,
                "markdown": str,  # Markdown 文件路径(如果没有则为空字符串)
                "sql": str,       # SQL 文件路径(如果没有则为空字符串)
                "json": str       # JSON 文件路径(如果没有则为空字符串)
            }
            
        处理流程:
            1. 生成安全的文件名(移除特殊字符)
            2. 生成 Markdown 文件(如果有 markdown 内容)
            3. 生成 SQL 文件(如果有 sql 内容)
            4. 生成 JSON 文件(如果有 table_structure)
        """
        ind_id = scheme.get("indicator_id", "unknown")
        ind_name = scheme.get("indicator_name", "unknown")
        
        # 生成安全的文件名(移除空格和特殊字符)
        safe_name = self._sanitize_filename(ind_name)
        # 添加时间戳以避免文件名冲突
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        base_filename = f"{safe_name}_{timestamp}"
        
        # 初始化返回结果
        generated = {
            "indicator_id": ind_id,
            "indicator_name": ind_name,
            "markdown": "",
            "sql": "",
            "json": ""
        }
        
        # 1. 生成 Markdown 文件
        markdown = scheme.get("markdown", "")
        if not markdown and indicator:
            # 如果没有提供 markdown,则从 indicator 对象生成
            markdown = indicator.to_markdown()
        
        if markdown:
            md_path = self.output_dir / f"{base_filename}.md"
            with open(md_path, 'w', encoding='utf-8') as f:
                f.write(markdown)
            generated["markdown"] = str(md_path)
            logger.info(f"生成 Markdown 文件: {md_path}")
        
        # 2. 生成 SQL 文件
        sql = scheme.get("sql", "")
        if sql:
            sql_path = self.output_dir / f"{base_filename}.sql"
            with open(sql_path, 'w', encoding='utf-8') as f:
                f.write(sql)
            generated["sql"] = str(sql_path)
            logger.info(f"生成 SQL 文件: {sql_path}")
        
        # 3. 生成 JSON 文件(表结构)
        table_structure = scheme.get("table_structure", [])
        if table_structure:
            json_path = self.output_dir / f"{base_filename}.json"
            with open(json_path, 'w', encoding='utf-8') as f:
                json.dump(table_structure, f, ensure_ascii=False, indent=2)
            generated["json"] = str(json_path)
            logger.info(f"生成 JSON 文件: {json_path}")
        
        return generated
    
    def _generate_indicator_set_json(
        self,
        indicator_set: IndicatorSet,
        schemes: List[Dict[str, Any]]
    ) -> str:
        """
        生成指标集的合并 JSON 文件
        
        内部方法:将整个指标集和所有方案合并成一个 JSON 文件。
        
        参数:
            indicator_set (IndicatorSet): 指标集对象
            schemes (List[Dict]): 建模方案列表
            
        返回:
            str: 生成的 JSON 文件路径
            
        输出格式:
            {
                "set_id": "...",
                "set_name": "...",
                ...
                "indicators": [...],
                "schemes": [...],
                "generated_at": "...",
                "version": "3.0"
            }
        """
        # 构建合并数据(指标集字典表示)
        combined = indicator_set.to_dict()
        
        # 添加建模方案
        combined["schemes"] = schemes
        
        # 添加元数据(生成时间、版本号)
        combined["generated_at"] = datetime.now().isoformat()
        combined["version"] = "3.0"
        
        # 保存到文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_name = self._sanitize_filename(indicator_set.set_name)
        json_path = self.output_dir / f"{safe_name}_{timestamp}_indicator_set.json"
        
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(combined, f, ensure_ascii=False, indent=2)
        
        logger.info(f"生成指标集 JSON 文件: {json_path}")
        
        return str(json_path)
    
    def _generate_combined_markdown(
        self,
        indicator_set: IndicatorSet,
        schemes: List[Dict[str, Any]]
    ) -> str:
        """
        生成指标集的合并 Markdown 文件
        
        内部方法:将指标集说明和所有方案的详细信息合并成一个 Markdown 文件。
        
        参数:
            indicator_set (IndicatorSet): 指标集对象
            schemes (List[Dict]): 建模方案列表
            
        返回:
            str: 生成的 Markdown 文件路径
            
        输出格式:
            # 指标集名称
            
            ## 指标集说明
            ...
            
            ## 指标方案详情
            
            ### 1. 指标名称
            
            **SQL 查询**:
            ...
            
            **表结构**:
            ...
        """
        # 开始构建 Markdown 内容(先添加指标集的 Markdown)
        md = indicator_set.to_markdown()
        
        # 添加方案详情章节
        md += "\n\n---\n\n## 指标方案详情\n\n"
        
        # 遍历所有方案,添加详细信息
        for i, scheme in enumerate(schemes, 1):
            ind_name = scheme.get("indicator_name", f"指标{i}")
            sql = scheme.get("sql", "")
            table_structure = scheme.get("table_structure", [])
            
            md += f"### {i}. {ind_name}\n\n"
            
            # 添加 SQL 查询
            if sql:
                md += f"**SQL 查询**:\n\n```sql\n{sql}\n```\n\n"
            
            # 添加表结构(JSON 格式)
            if table_structure:
                md += f"**表结构**:\n\n```json\n{json.dumps(table_structure, ensure_ascii=False, indent=2)}\n```\n\n"
            
            md += "---\n\n"
        
        # 保存到文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_name = self._sanitize_filename(indicator_set.set_name)
        md_path = self.output_dir / f"{safe_name}_{timestamp}_combined.md"
        
        with open(md_path, 'w', encoding='utf-8') as f:
            f.write(md)
        
        logger.info(f"生成合并 Markdown 文件: {md_path}")
        
        return str(md_path)
    
    def _generate_combined_sql(
        self,
        schemes: List[Dict[str, Any]]
    ) -> str:
        """
        生成所有指标的合并 SQL 文件
        
        内部方法:将所有指标的 SQL 查询合并成一个 SQL 文件,
        每个指标的 SQL 用注释分隔。
        
        参数:
            schemes (List[Dict]): 建模方案列表
            
        返回:
            str: 生成的 SQL 文件路径
            
        输出格式:
            -- ============ 指标名称1 ============
            
            SELECT ...
            
            -- ============ 指标名称2 ============
            
            SELECT ...
        """
        sql_parts = []
        
        # 遍历所有方案,收集 SQL
        for i, scheme in enumerate(schemes, 1):
            ind_name = scheme.get("indicator_name", f"指标{i}")
            sql = scheme.get("sql", "")
            
            if sql:
                # 用注释分隔每个指标的 SQL
                sql_parts.append(f"-- ============ {ind_name} ============\n\n{sql}\n")
        
        # 用两个换行符连接所有 SQL
        combined_sql = "\n\n".join(sql_parts)
        
        # 保存到文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        sql_path = self.output_dir / f"combined_{timestamp}.sql"
        
        with open(sql_path, 'w', encoding='utf-8') as f:
            f.write(combined_sql)
        
        logger.info(f"生成合并 SQL 文件: {sql_path}")
        
        return str(sql_path)
    
    def _generate_bi_design_markdown(
        self,
        bi_design: Dict[str, Any],
        indicator_set: IndicatorSet
    ) -> str:
        """
        生成 BI 设计 Markdown 文件
        
        内部方法:将 BI 设计方案生成 Markdown 文档,
        包含图表推荐、仪表板布局等。
        
        参数:
            bi_design (Dict[str, Any]): BI 设计方案
            indicator_set (IndicatorSet): 指标集对象(用于上下文)
            
        返回:
            str: 生成的 Markdown 文件路径
            
        输出格式:
            # 指标集名称 - BI设计方案
            
            ## 图表推荐
            
            ### 1. 图表标题
            - **图表类型**: ...
            - **使用指标**: ...
            - **使用场景**: ...
            
            ## 仪表板布局
            ...
        """
        # 优先使用 BI 设计中的 Markdown(如果已生成)
        md = bi_design.get("markdown", "")
        
        if not md:
            # 如果没有预生成的 Markdown,则从 charts 和 dashboard_layout 生成
            charts = bi_design.get("charts", [])
            dashboard_layout = bi_design.get("dashboard_layout", "")
            
            md = f"# {indicator_set.set_name} - BI设计方案\n\n"
            md += f"## 图表推荐\n\n"
            
            # 遍历所有图表推荐
            for i, chart in enumerate(charts, 1):
                md += f"### {i}. {chart.get('title', '图表')}\n\n"
                md += f"- **图表类型**: {chart.get('chart_type', '未知')}\n"
                md += f"- **使用指标**: {', '.join(chart.get('indicators', []))}\n"
                md += f"- **使用场景**: {chart.get('usage_scenario', '通用')}\n\n"
                
                # 添加图表示意图(如果可用)
                diagram = chart.get("markdown_diagram", "")
                if diagram:
                    md += f"{diagram}\n\n"
            
            # 添加仪表板布局说明
            md += f"\n\n## 仪表板布局\n\n{dashboard_layout}\n"
        
        # 保存到文件
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_name = self._sanitize_filename(indicator_set.set_name)
        md_path = self.output_dir / f"{safe_name}_{timestamp}_bi_design.md"
        
        with open(md_path, 'w', encoding='utf-8') as f:
            f.write(md)
        
        logger.info(f"生成 BI 设计 Markdown 文件: {md_path}")
        
        return str(md_path)
    
    def _save_indicator_set_json(self, indicator_set: IndicatorSet) -> str:
        """
        保存指标集为 JSON 文件
        
        内部方法:将指标集对象保存为独立的 JSON 文件。
        
        参数:
            indicator_set (IndicatorSet): 指标集对象
            
        返回:
            str: 保存的 JSON 文件路径
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_name = self._sanitize_filename(indicator_set.set_name)
        json_path = self.output_dir / f"{safe_name}_{timestamp}_set.json"
        
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(indicator_set.to_dict(), f, ensure_ascii=False, indent=2)
        
        logger.info(f"保存指标集 JSON 文件: {json_path}")
        
        return str(json_path)
    
    def _save_indicator_set_markdown(self, indicator_set: IndicatorSet) -> str:
        """
        保存指标集为 Markdown 文件
        
        内部方法:将指标集对象保存为独立的 Markdown 文件。
        
        参数:
            indicator_set (IndicatorSet): 指标集对象
            
        返回:
            str: 保存的 Markdown 文件路径
        """
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        safe_name = self._sanitize_filename(indicator_set.set_name)
        md_path = self.output_dir / f"{safe_name}_{timestamp}_set.md"
        
        with open(md_path, 'w', encoding='utf-8') as f:
            f.write(indicator_set.to_markdown())
        
        logger.info(f"保存指标集 Markdown 文件: {md_path}")
        
        return str(md_path)
    
    def _sanitize_filename(self, name: str) -> str:
        """
        清理文件名,移除不合法字符
        
        内部方法:将指标名称转换为安全的文件名,
        移除空格和特殊字符,仅保留字母、数字、下划线和连字符。
        
        参数:
            name (str): 原始名称(可能是中文指标名称)
            
        返回:
            str: 清理后的安全文件名
            
        示例:
            >>> _sanitize_filename("日订单金额")
            "日订单金额"  # 中文通常没问题
            >>> _sanitize_filename("GMV (商品交易总额)")
            "GMV_商品交易总额"
        """
        # 替换空格为下划线
        safe = name.replace(' ', '_')
        # 仅保留字母、数字、下划线和连字符
        safe = ''.join(c for c in safe if c.isalnum() or c in ['_', '-'])
        return safe if safe else 'indicator'
    
    def get_output_dir(self) -> Path:
        """
        获取输出目录路径
        
        返回:
            Path: 输出目录的 Path 对象
        """
        return self.output_dir
    

if __name__ == "__main__":
    # 测试 FileGenerator 功能
    import logging
    logging.basicConfig(level=logging.INFO)
    
    from models.indicator import Indicator
    from models.indicator_set import IndicatorSet
    
    print("\n=== 测试 FileGenerator (v3.0) ===\n")
    
    # 创建测试指标
    ind1 = Indicator(
        indicator_id="ind_001",
        indicator_name="GMV",
        business_meaning="商品交易总额",
        calculation_logic="SUM(order_amount)",
        dimensions=["date", "category"],
        metrics=["order_amount"],
        time_granularity="日",
        update_frequency="实时",
        data_source="fact_order"
    )
    
    ind2 = Indicator(
        indicator_id="ind_002",
        indicator_name="订单量",
        business_meaning="每日订单总数",
        calculation_logic="COUNT(order_id)",
        dimensions=["date"],
        metrics=["order_id"],
        time_granularity="日",
        update_frequency="实时",
        data_source="fact_order"
    )
    
    # 创建指标集
    indicator_set = IndicatorSet(
        set_id="set_test_001",
        set_name="测试指标集",
        business_domain="电商",
        analysis_purpose="测试文件生成",
        indicators=[ind1, ind2]
    )
    
    # 创建模拟方案
    schemes = [
        {
            "indicator_id": "ind_001",
            "indicator_name": "GMV",
            "markdown": "# GMV\n\n商品交易总额...",
            "sql": "SELECT SUM(order_amount) FROM fact_order",
            "table_structure": [{"table_name": "fact_order", "columns": []}]
        },
        {
            "indicator_id": "ind_002",
            "indicator_name": "订单量",
            "markdown": "# 订单量\n\n每日订单总数...",
            "sql": "SELECT COUNT(order_id) FROM fact_order",
            "table_structure": [{"table_name": "fact_order", "columns": []}]
        }
    ]
    
    # 测试 FileGenerator
    generator = FileGenerator()
    
    # 测试 generate_all 方法
    print("测试 1: 生成所有文件(批量)")
    files = generator.generate_all(indicator_set, schemes)
    print(f"✅ 生成了 {len(files['files'])} 个指标文件")
    print(f"   合并 Markdown: {files['markdown']}")
    print(f"   合并 SQL: {files['sql']}")
    print(f"   指标集 JSON: {files['indicator_set']}")
    
    print("\n✅ FileGenerator 测试完成!")