"""CLI命令体系模块"""

import argparse
import json
import sys
import os
from typing import Dict, Any, Optional
from hos_m2f.engine.engine import Engine


class CLI:
    """命令行接口"""
    
    def __init__(self):
        self.engine = Engine()
        self.parser = argparse.ArgumentParser(
            prog='hos-m2f',
            description='HOS-M2F v1.0 - Content Compiler Engine for AI Writing and Professional Document Production',
            epilog='For more information, visit the project documentation.'
        )
        self.subparsers = self.parser.add_subparsers(dest='command', help='Available commands')
        self._setup_commands()
    
    def _setup_commands(self):
        """设置命令"""
        # build命令
        build_parser = self.subparsers.add_parser('build', help='Build document from Markdown')
        build_parser.add_argument('input', help='Input Markdown file')
        build_parser.add_argument('output', help='Output file path')
        build_parser.add_argument('--mode', default='paper', help='Document mode')
        build_parser.add_argument('--format', choices=['epub', 'pdf', 'docx', 'json', 'html', 'xml', 'xlsx'], default='epub', help='Output format')
        build_parser.add_argument('--options', type=str, default='{}', help='Additional options as JSON string')
        
        # check命令
        check_parser = self.subparsers.add_parser('check', help='Check document structure and compliance')
        check_parser.add_argument('input', help='Input Markdown file')
        check_parser.add_argument('--mode', default='paper', help='Document mode')
        check_parser.add_argument('--options', type=str, default='{}', help='Additional options as JSON string')
        
        # parse命令
        parse_parser = self.subparsers.add_parser('parse', help='Parse Markdown content and output structured data')
        parse_parser.add_argument('input', help='Input Markdown file')
        parse_parser.add_argument('--mode', default='paper', help='Document mode')
        parse_parser.add_argument('--output', help='Output JSON file (default: stdout)')
        parse_parser.add_argument('--options', type=str, default='{}', help='Additional options as JSON string')
        
        # convert命令
        convert_parser = self.subparsers.add_parser('convert', help='Convert between different formats')
        convert_parser.add_argument('input', help='Input file')
        convert_parser.add_argument('output', help='Output file path')
        convert_parser.add_argument('--from', dest='from_format', required=True, choices=['md', 'markdown', 'docx', 'json', 'epub', 'html', 'xml', 'pdf', 'xlsx'], help='Input format')
        convert_parser.add_argument('--to', dest='to_format', required=True, choices=['md', 'markdown', 'docx', 'json', 'epub', 'html', 'xml', 'pdf', 'xlsx'], help='Output format')
        convert_parser.add_argument('--options', type=str, default='{}', help='Additional options as JSON string')
        convert_parser.add_argument('--encrypt', action='store_true', help='Enable encryption mode (degrade images for demo)')
        
        # preview命令
        preview_parser = self.subparsers.add_parser('preview', help='Start preview server')
        preview_parser.add_argument('--port', type=int, default=8000, help='Port to run the server on')
        
        # info命令
        info_parser = self.subparsers.add_parser('info', help='Show information about supported modes and formats')
        info_parser.add_argument('--detail', action='store_true', help='Show detailed information')
        
        # validate命令
        validate_parser = self.subparsers.add_parser('validate', help='Validate options for a specific mode')
        validate_parser.add_argument('--mode', required=True, help='Document mode')
        validate_parser.add_argument('--options', type=str, required=True, help='Options to validate as JSON string')
        
        # batch命令
        batch_parser = self.subparsers.add_parser('batch', help='Batch process directory')
        batch_parser.add_argument('input', help='Input directory')
        batch_parser.add_argument('--format', choices=['epub', 'pdf', 'docx', 'json', 'html', 'xml', 'xlsx'], default='epub', help='Output format')
        batch_parser.add_argument('--options', type=str, default='{}', help='Additional options as JSON string')
        batch_parser.add_argument('--workers', type=int, default=4, help='Number of parallel workers')
        
        # quality命令
        quality_parser = self.subparsers.add_parser('quality', help='Analyze document quality')
        quality_parser.add_argument('input', help='Input file or directory')
        quality_parser.add_argument('--output', help='Output report file (default: logs/report.json)')
        
        # mcp命令
        mcp_parser = self.subparsers.add_parser('mcp', help='Start MCP service')
        mcp_parser.add_argument('--port', type=int, default=8000, help='Service port')
        mcp_parser.add_argument('--host', default='0.0.0.0', help='Service host')
        mcp_parser.add_argument('--timeout', type=int, default=30, help='Request timeout in seconds')
        mcp_parser.add_argument('--max-concurrent', type=int, default=10, help='Maximum concurrent requests')
        
        # pipeline命令
        pipeline_parser = self.subparsers.add_parser('pipeline', help='Run AI document automation pipeline')
        pipeline_subparsers = pipeline_parser.add_subparsers(dest='pipeline_action', help='Pipeline actions')
        
        # pipeline run命令
        run_parser = pipeline_subparsers.add_parser('run', help='Run full pipeline')
        run_parser.add_argument('input', help='Input DOCX file')
        run_parser.add_argument('--ai-content', required=True, help='AI generated content as JSON string')
        run_parser.add_argument('--ai-instructions', required=True, help='AI instructions as JSON string')
        run_parser.add_argument('--output-dir', help='Output directory')
        
        # pipeline template命令
        template_parser = pipeline_subparsers.add_parser('template', help='Generate XML template')
        template_parser.add_argument('input', help='Input XML file')
        template_parser.add_argument('--output', help='Output template file')
        
        # pipeline schema命令
        schema_parser = pipeline_subparsers.add_parser('schema', help='Generate Schema from XML')
        schema_parser.add_argument('input', help='Input XML file')
        schema_parser.add_argument('--output', help='Output schema file')
        schema_parser.add_argument('--format', choices=['simple', 'json_schema', 'yaml'], default='json_schema', help='Schema format')
        
        # pipeline prompt命令
        prompt_parser = pipeline_subparsers.add_parser('prompt', help='Generate AI prompt')
        prompt_parser.add_argument('--task', required=True, choices=['content_generation', 'xml_modification'], help='Task type')
        prompt_parser.add_argument('--schema', help='Schema file for context')
        prompt_parser.add_argument('--context', help='Additional context for prompt')
    
    def run(self, args=None):
        """运行命令
        
        Args:
            args: 命令行参数
            
        Returns:
            int: 退出码
        """
        if args is None:
            args = sys.argv[1:]
        
        parsed_args = self.parser.parse_args(args)
        
        if not parsed_args.command:
            self.parser.print_help()
            return 1
        
        try:
            if parsed_args.command == 'build':
                return self._run_build(parsed_args)
            elif parsed_args.command == 'check':
                return self._run_check(parsed_args)
            elif parsed_args.command == 'parse':
                return self._run_parse(parsed_args)
            elif parsed_args.command == 'convert':
                return self._run_convert(parsed_args)
            elif parsed_args.command == 'preview':
                return self._run_preview(parsed_args)
            elif parsed_args.command == 'info':
                return self._run_info(parsed_args)
            elif parsed_args.command == 'validate':
                return self._run_validate(parsed_args)
            elif parsed_args.command == 'batch':
                return self._run_batch(parsed_args)
            elif parsed_args.command == 'quality':
                return self._run_quality(parsed_args)
            elif parsed_args.command == 'mcp':
                return self._run_mcp(parsed_args)
            elif parsed_args.command == 'pipeline':
                return self._run_pipeline(parsed_args)
            else:
                self.parser.print_help()
                return 1
        except Exception as e:
            print(f'Error: {e}', file=sys.stderr)
            return 1
    
    def _run_build(self, args):
        """运行build命令"""
        # 读取输入文件
        with open(args.input, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析选项
        options = json.loads(args.options)
        
        # 构建文档
        result = self.engine.build(content, args.mode, args.format, options)
        
        # 写入输出文件
        with open(args.output, 'wb') as f:
            f.write(result.binary)
        
        print(f'Successfully built {args.output}')
        print(f'Output format: {result.output_format}')
        if result.metadata:
            print('Metadata:', json.dumps(result.metadata, ensure_ascii=False, indent=2))
        
        return 0
    
    def _run_check(self, args):
        """运行check命令"""
        # 读取输入文件
        with open(args.input, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析选项
        options = json.loads(args.options)
        
        # 检查文档
        result = self.engine.check(content, args.mode, options)
        
        # 输出结果
        print('Check result:')
        print(json.dumps(result, ensure_ascii=False, indent=2))
        
        # 检查是否有问题
        if 'compliance' in result and not result['compliance'].get('compliant', True):
            print('\nIssues found:', file=sys.stderr)
            for issue in result['compliance'].get('issues', []):
                print(f'  - {issue}', file=sys.stderr)
            return 1
        
        print('\nNo issues found!')
        return 0
    
    def _run_parse(self, args):
        """运行parse命令"""
        # 读取输入文件
        with open(args.input, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析选项
        options = json.loads(args.options)
        
        # 根据模式选择解析器
        if args.mode == 'book':
            from hos_m2f.structure.book_parser import BookParser
            parser = BookParser()
        elif args.mode == 'patent':
            from hos_m2f.structure.patent_parser import PatentParser
            parser = PatentParser()
        elif args.mode == 'sop':
            from hos_m2f.structure.sop_parser import SOPParser
            parser = SOPParser()
        else:
            from hos_m2f.structure.semantic_parser import SemanticParser
            parser = SemanticParser()
        
        # 解析内容
        result = parser.parse(content, options)
        
        # 输出结果
        output_data = json.dumps(result, ensure_ascii=False, indent=2)
        
        if args.output:
            with open(args.output, 'w', encoding='utf-8') as f:
                f.write(output_data)
            print(f'Successfully parsed to {args.output}')
        else:
            print(output_data)
        
        return 0
    
    def _run_preview(self, args):
        """运行preview命令"""
        print('Preview server is not available in this version')
        return 1
    
    def _run_info(self, args):
        """运行info命令"""
        print('HOS-M2F v1.0 - Content Compiler Engine')
        print('=====================================')
        
        # 显示支持的模式
        print('\nSupported modes:')
        modes = self.engine.get_supported_modes()
        for mode, description in modes.items():
            print(f'  - {mode}: {description}')
        
        # 显示支持的格式
        print('\nSupported output formats:')
        formats = self.engine.get_supported_formats()
        for fmt, description in formats.items():
            print(f'  - {fmt}: {description}')
        
        if args.detail:
            print('\nDetailed information:')
            print('\nBook mode:')
            print('  Description: Supports chapter structure recognition, TOC generation, metadata packaging, cover recognition')
            print('  Output formats: epub, pdf, docx, json, xlsx')
            
            print('\nPatent mode:')
            print('  Description: Supports automatic claim numbering, patent paragraph indentation, figure numbering')
            print('  Output formats: pdf, docx, json, xlsx')
            
            print('\nSOP mode:')
            print('  Description: Supports step numbering, checklist tabularization, risk level identification')
            print('  Output formats: pdf, docx, json, xlsx')
            
            print('\nPaper mode:')
            print('  Description: Supports technical documents and paper formatting')
            print('  Output formats: pdf, docx, json, xlsx')
        
        return 0
    
    def _run_validate(self, args):
        """运行validate命令"""
        # 解析选项
        options = json.loads(args.options)
        
        # 验证选项
        from hos_m2f.ide.api import IDEAPI
        api = IDEAPI()
        result = api.validate_options(args.mode, options)
        
        # 输出结果
        print('Validation result:')
        print(json.dumps(result, ensure_ascii=False, indent=2))
        
        if not result['valid']:
            print('\nValidation failed:', file=sys.stderr)
            for error in result['errors']:
                print(f'  - {error}', file=sys.stderr)
            return 1
        
        print('\nValidation passed!')
        return 0
    
    def _run_batch(self, args):
        """运行batch命令"""
        # 解析选项
        options = json.loads(args.options)
        
        # 执行批量处理
        from hos_m2f.batch.batch_processor import BatchProcessor
        processor = BatchProcessor(max_workers=args.workers)
        result = processor.process_directory(args.input, args.format, options)
        
        # 输出结果
        print('Batch processing completed!')
        print(f'Processed: {result.get("processed", 0)} files')
        print(f'Success: {result.get("success_count", 0)}')
        print(f'Errors: {result.get("error_count", 0)}')
        
        if result.get("error_count", 0) > 0:
            print('\nErrors:')
            for item in result.get("results", []):
                if not item.get("success", False):
                    print(f'  - {item.get("input_path", "")}: {item.get("error", "Unknown error")}')
            return 1
        
        return 0
    
    def _run_quality(self, args):
        """运行quality命令"""
        # 执行质量分析
        from hos_m2f.quality.quality_control import QualityControl
        qc = QualityControl()
        
        # 检查输入是文件还是目录
        if os.path.isdir(args.input):
            result = qc.batch_analyze(args.input)
            print('Batch quality analysis completed!')
            print(f'Analyzed: {result.get("statistics", {}).get("total_files", 0)} files')
            print(f'Total issues: {result.get("statistics", {}).get("total_issues", 0)}')
        else:
            result = qc.analyze_document(args.input)
            print('Quality analysis completed!')
            print(f'File: {result.get("file", "")}')
            print(f'Total issues: {result.get("statistics", {}).get("total_issues", 0)}')
            
            if result.get("issues", []):
                print('\nIssues:')
                for issue in result.get("issues", []):
                    print(f'  - [{issue.get("severity", "info")}] {issue.get("type", "")}: {issue.get("message", "")}')
        
        return 0
    
    def _run_mcp(self, args):
        """运行mcp命令，启动MCP服务"""
        try:
            from flask import Flask, request, jsonify
            import threading
            
            # 创建Flask应用
            app = Flask(__name__)
            
            # 获取参数
            port = args.port
            host = args.host
            timeout = args.timeout
            max_concurrent = args.max_concurrent
            
            # 存储当前并发请求数
            current_concurrent = 0
            concurrent_lock = threading.Lock()
            
            @app.route('/convert', methods=['POST'])
            def convert():
                """转换文档格式"""
                nonlocal current_concurrent
                
                # 检查并发请求数
                with concurrent_lock:
                    if current_concurrent >= max_concurrent:
                        return jsonify({"error": "Too many concurrent requests"}), 429
                    current_concurrent += 1
                
                try:
                    # 获取请求数据
                    data = request.json
                    if not data:
                        return jsonify({"error": "Invalid request data"}), 400
                    
                    # 提取参数
                    input_format = data.get('input_format')
                    output_format = data.get('output_format')
                    content = data.get('content')
                    options = data.get('options', {})
                    
                    if not all([input_format, output_format, content]):
                        return jsonify({"error": "Missing required parameters"}), 400
                    
                    # 执行转换
                    result = self.engine.convert_content(
                        input_format=input_format,
                        output_format=output_format,
                        input_content=content.encode('utf-8'),
                        options=options
                    )
                    
                    # 返回结果
                    return result
                except Exception as e:
                    return jsonify({"error": str(e)}), 500
                finally:
                    # 减少并发请求数
                    with concurrent_lock:
                        current_concurrent -= 1
            
            @app.route('/build', methods=['POST'])
            def build():
                """构建文档"""
                nonlocal current_concurrent
                
                # 检查并发请求数
                with concurrent_lock:
                    if current_concurrent >= max_concurrent:
                        return jsonify({"error": "Too many concurrent requests"}), 429
                    current_concurrent += 1
                
                try:
                    # 获取请求数据
                    data = request.json
                    if not data:
                        return jsonify({"error": "Invalid request data"}), 400
                    
                    # 提取参数
                    content = data.get('content')
                    mode = data.get('mode', 'paper')
                    output_format = data.get('output_format', 'docx')
                    options = data.get('options', {})
                    
                    if not content:
                        return jsonify({"error": "Missing required parameter: content"}), 400
                    
                    # 执行构建
                    result = self.engine.build(
                        content=content,
                        mode=mode,
                        format=output_format,
                        options=options
                    )
                    
                    # 返回结果
                    return result['binary']
                except Exception as e:
                    return jsonify({"error": str(e)}), 500
                finally:
                    # 减少并发请求数
                    with concurrent_lock:
                        current_concurrent -= 1
            
            @app.route('/check', methods=['POST'])
            def check():
                """校验文档"""
                nonlocal current_concurrent
                
                # 检查并发请求数
                with concurrent_lock:
                    if current_concurrent >= max_concurrent:
                        return jsonify({"error": "Too many concurrent requests"}), 429
                    current_concurrent += 1
                
                try:
                    # 获取请求数据
                    data = request.json
                    if not data:
                        return jsonify({"error": "Invalid request data"}), 400
                    
                    # 提取参数
                    content = data.get('content')
                    mode = data.get('mode', 'paper')
                    options = data.get('options', {})
                    
                    if not content:
                        return jsonify({"error": "Missing required parameter: content"}), 400
                    
                    # 执行校验
                    result = self.engine.check(
                        content=content,
                        mode=mode,
                        options=options
                    )
                    
                    # 返回结果
                    return jsonify(result)
                except Exception as e:
                    return jsonify({"error": str(e)}), 500
                finally:
                    # 减少并发请求数
                    with concurrent_lock:
                        current_concurrent -= 1
            
            @app.route('/info', methods=['GET'])
            def info():
                """获取服务信息"""
                try:
                    # 获取支持的模式和格式
                    modes = self.engine.get_supported_modes()
                    formats = self.engine.get_supported_formats()
                    
                    # 构建信息响应
                    info_data = {
                        "name": "HOS-M2F MCP Service",
                        "version": "1.0.0",
                        "supported_modes": modes,
                        "supported_formats": formats,
                        "status": "running",
                        "config": {
                            "port": port,
                            "host": host,
                            "timeout": timeout,
                            "max_concurrent": max_concurrent
                        }
                    }
                    
                    # 返回结果
                    return jsonify(info_data)
                except Exception as e:
                    return jsonify({"error": str(e)}), 500
            
            @app.route('/pipeline', methods=['POST'])
            def pipeline():
                """处理AI流水线请求"""
                nonlocal current_concurrent
                
                # 检查并发请求数
                with concurrent_lock:
                    if current_concurrent >= max_concurrent:
                        return jsonify({"error": "Too many concurrent requests"}), 429
                    current_concurrent += 1
                
                try:
                    # 获取请求数据
                    data = request.json
                    if not data:
                        return jsonify({"error": "Invalid request data"}), 400
                    
                    # 提取参数
                    action = data.get('action')
                    input_data = data.get('input')
                    ai_content = data.get('ai_content')
                    ai_instructions = data.get('ai_instructions')
                    options = data.get('options', {})
                    
                    if not action:
                        return jsonify({"error": "Missing required parameter: action"}), 400
                    
                    # 处理不同的流水线操作
                    if action == 'run':
                        # 运行完整流水线
                        if not all([input_data, ai_content, ai_instructions]):
                            return jsonify({"error": "Missing required parameters for 'run' action"}), 400
                        
                        # 保存输入数据为临时文件
                        import tempfile
                        import base64
                        
                        # 检查输入是否为base64编码
                        if isinstance(input_data, str) and input_data.startswith('base64:'):
                            # 解码base64数据
                            base64_data = input_data.split(':', 1)[1]
                            docx_content = base64.b64decode(base64_data)
                            
                            # 创建临时DOCX文件
                            with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as f:
                                f.write(docx_content)
                                temp_docx_path = f.name
                            
                            try:
                                # 运行流水线
                                result = self.engine.run_ai_pipeline(
                                    temp_docx_path,
                                    ai_content,
                                    ai_instructions,
                                    output_dir=options.get('output_dir')
                                )
                                return jsonify(result)
                            finally:
                                # 清理临时文件
                                if os.path.exists(temp_docx_path):
                                    os.unlink(temp_docx_path)
                        else:
                            # 输入为文件路径
                            result = self.engine.run_ai_pipeline(
                                input_data,
                                ai_content,
                                ai_instructions,
                                output_dir=options.get('output_dir')
                            )
                            return jsonify(result)
                    elif action == 'component':
                        # 获取单个组件
                        component_name = data.get('component')
                        if not component_name:
                            return jsonify({"error": "Missing required parameter: component"}), 400
                        
                        try:
                            component = self.engine.get_ai_pipeline_component(component_name)
                            return jsonify({"success": True, "component": component_name})
                        except Exception as e:
                            return jsonify({"error": str(e)}), 400
                    elif action == 'prompt':
                        # 生成AI提示词
                        task_type = data.get('task_type')
                        if not task_type:
                            return jsonify({"error": "Missing required parameter: task_type"}), 400
                        
                        prompt = self.engine.generate_ai_prompt(
                            task_type,
                            **options
                        )
                        return jsonify({"prompt": prompt})
                    else:
                        return jsonify({"error": f"Unknown action: {action}"}), 400
                except Exception as e:
                    return jsonify({"error": str(e)}), 500
                finally:
                    # 减少并发请求数
                    with concurrent_lock:
                        current_concurrent -= 1
            
            # 启动服务
            print(f"Starting MCP service on {host}:{port}...")
            print(f"Max concurrent requests: {max_concurrent}")
            print(f"Request timeout: {timeout} seconds")
            print("\nAvailable endpoints:")
            print("  POST /convert - Convert document format")
            print("  POST /build - Build document")
            print("  POST /check - Check document")
            print("  GET /info - Get service information")
            print("  POST /pipeline - Run AI document automation pipeline")
            print("\nPress Ctrl+C to stop the service")
            
            # 启动Flask应用
            app.run(host=host, port=port, debug=False, threaded=True)
            
        except ImportError:
            print("Error: Flask is required for MCP service. Please install it with 'pip install flask'")
            return 1
        except Exception as e:
            print(f"Error starting MCP service: {e}")
            return 1
    
    def _run_convert(self, args):
        """运行convert命令"""
        # 解析选项
        options = json.loads(args.options)
        
        # 添加加密模式选项
        if hasattr(args, 'encrypt') and args.encrypt:
            options['encrypt'] = True
        
        # 添加基础目录选项
        options['base_dir'] = os.path.dirname(os.path.abspath(args.input)) or '.'
        
        # 执行转换
        result = self.engine.convert(args.input, args.output, args.from_format, args.to_format, options)
        
        # 输出结果
        print(f'Successfully converted {args.input} to {args.output}')
        print(f'From format: {args.from_format}')
        print(f'To format: {args.to_format}')
        if result['metadata']:
            print('Metadata:', json.dumps(result['metadata'], ensure_ascii=False, indent=2))
        
        return 0
    
    def _run_pipeline(self, args):
        """运行pipeline命令"""
        if not args.pipeline_action:
            print('Error: Pipeline action required', file=sys.stderr)
            return 1
        
        try:
            if args.pipeline_action == 'run':
                return self._run_pipeline_run(args)
            elif args.pipeline_action == 'template':
                return self._run_pipeline_template(args)
            elif args.pipeline_action == 'schema':
                return self._run_pipeline_schema(args)
            elif args.pipeline_action == 'prompt':
                return self._run_pipeline_prompt(args)
            else:
                print(f'Error: Unknown pipeline action: {args.pipeline_action}', file=sys.stderr)
                return 1
        except Exception as e:
            print(f'Error: {e}', file=sys.stderr)
            return 1
    
    def _run_pipeline_run(self, args):
        """运行完整流水线"""
        from hos_m2f.pipeline import PipelineCoordinator
        
        # 初始化流水线协调器
        coordinator = PipelineCoordinator()
        
        # 运行完整流水线
        result = coordinator.full_pipeline(
            args.input,
            args.ai_content,
            args.ai_instructions,
            output_dir=args.output_dir
        )
        
        # 输出结果
        print(f'Pipeline status: {result.get("status", "unknown")}')
        
        if result.get('status') == 'success':
            print('Pipeline completed successfully!')
            print('Output files:')
            for key, value in result.items():
                if key not in ['status', 'output_dir']:
                    print(f'  - {key}: {value}')
            return 0
        else:
            print(f'Pipeline failed: {result.get("error", "Unknown error")}', file=sys.stderr)
            return 1
    
    def _run_pipeline_template(self, args):
        """生成XML模板"""
        from hos_m2f.pipeline import XMLTemplater
        
        # 读取输入XML文件
        encodings = ['utf-8', 'gbk', 'ansi']
        xml_content = None
        
        for encoding in encodings:
            try:
                with open(args.input, 'r', encoding=encoding) as f:
                    xml_content = f.read()
                break
            except UnicodeDecodeError:
                continue
        
        if xml_content is None:
            print('Error: Failed to read input XML file', file=sys.stderr)
            return 1
        
        # 生成模板
        templater = XMLTemplater()
        template_xml, variable_map = templater.template_auto(xml_content)
        
        # 输出结果
        if args.output:
            with open(args.output, 'w', encoding='utf-8') as f:
                f.write(template_xml)
            print(f'Successfully generated template: {args.output}')
            
            # 保存变量映射表
            map_output = args.output.replace('.xml', '_map.json')
            with open(map_output, 'w', encoding='utf-8') as f:
                json.dump(variable_map, f, ensure_ascii=False, indent=2)
            print(f'Successfully generated variable map: {map_output}')
        else:
            print('Template XML:')
            print(template_xml)
            print('\nVariable map:')
            print(json.dumps(variable_map, ensure_ascii=False, indent=2))
        
        return 0
    
    def _run_pipeline_schema(self, args):
        """生成Schema"""
        from hos_m2f.pipeline import SchemaGenerator
        
        # 读取输入XML文件
        encodings = ['utf-8', 'gbk', 'ansi']
        xml_content = None
        
        for encoding in encodings:
            try:
                with open(args.input, 'r', encoding=encoding) as f:
                    xml_content = f.read()
                break
            except UnicodeDecodeError:
                continue
        
        if xml_content is None:
            print('Error: Failed to read input XML file', file=sys.stderr)
            return 1
        
        # 生成Schema
        generator = SchemaGenerator()
        schema = generator.generate_from_xml(xml_content, format=args.format)
        
        # 输出结果
        if args.output:
            with open(args.output, 'w', encoding='utf-8') as f:
                if isinstance(schema, dict):
                    json.dump(schema, f, ensure_ascii=False, indent=2)
                else:
                    f.write(schema)
            print(f'Successfully generated schema: {args.output}')
        else:
            print('Schema:')
            if isinstance(schema, dict):
                print(json.dumps(schema, ensure_ascii=False, indent=2))
            else:
                print(schema)
        
        return 0
    
    def _run_pipeline_prompt(self, args):
        """生成AI提示词"""
        from hos_m2f.pipeline import AIPromptManager
        
        # 生成提示词
        manager = AIPromptManager()
        
        if args.task == 'content_generation':
            # 读取Schema文件（如果提供）
            schema = None
            if args.schema:
                try:
                    with open(args.schema, 'r', encoding='utf-8') as f:
                        schema = json.load(f)
                except Exception as e:
                    print(f'Warning: Failed to read schema file: {e}', file=sys.stderr)
            
            prompt = manager.get_content_generation_prompt(schema=schema, context=args.context)
        else:  # xml_modification
            prompt = manager.get_xml_modification_prompt(context=args.context)
        
        # 输出结果
        print('Generated prompt:')
        print(prompt)
        
        return 0


def main(args=None):
    """CLI命令入口点"""
    # 快速初始化
    cli = CLI()
    # 运行命令
    sys.exit(cli.run(args))

# 命令行入口
if __name__ == '__main__':
    main()
