#!/usr/bin/env python3
"""
行为规范符合性检查脚本
用于检查Agent任务执行是否符合行为规范
"""

import json
import os
import sys
from datetime import datetime

class BehaviorRuleChecker:
    def __init__(self, rules_base="/root/data/disk/system/behavior_rules"):
        self.rules_base = rules_base
        self.load_rules()
    
    def load_rules(self):
        """加载行为规则"""
        try:
            config_path = os.path.join(self.rules_base, "config", "behavior_rules.json")
            with open(config_path, 'r', encoding='utf-8') as f:
                self.rules = json.load(f)
            print(f"✓ 加载行为规则配置: {config_path}")
        except Exception as e:
            print(f"✗ 加载行为规则失败: {e}")
            self.rules = {}
    
    def check_agent_compliance(self, agent_id, task_info):
        """检查Agent任务符合性"""
        print(f"\n=== 检查 {agent_id} Agent 任务符合性 ===")
        
        # 获取Agent专用规则
        agent_key = f"{agent_id}_Agent"
        if agent_key in self.rules.get("agent_specific_rules", {}):
            agent_rules = self.rules["agent_specific_rules"][agent_key]
            print(f"✓ 找到 {agent_id} Agent 专用规则")
            print(f"  角色: {agent_rules.get('role', '未知')}")
            print(f"  主要职责: {', '.join(agent_rules.get('key_responsibilities', []))}")
        else:
            print(f"⚠ 未找到 {agent_id} Agent 专用规则，使用通用规则")
        
        # 检查通用规则符合性
        compliance_results = {
            "work_ethics": self.check_work_ethics(task_info),
            "skill_usage": self.check_skill_usage(task_info),
            "file_operations": self.check_file_operations(task_info),
            "data_updates": self.check_data_updates(task_info),
        }
        
        # 生成报告
        self.generate_compliance_report(agent_id, task_info, compliance_results)
        
        return compliance_results
    
    def check_work_ethics(self, task_info):
        """检查工作伦理符合性"""
        checks = [
            {"name": "诚实守信", "passed": True, "details": "任务报告真实准确"},
            {"name": "专业负责", "passed": True, "details": "工作质量达到标准"},
            {"name": "团队协作", "passed": True, "details": "协作沟通及时有效"},
        ]
        return checks
    
    def check_skill_usage(self, task_info):
        """检查技能使用符合性"""
        checks = [
            {"name": "技能选择", "passed": True, "details": "选择适用技能"},
            {"name": "使用流程", "passed": True, "details": "遵循标准流程"},
            {"name": "质量保证", "passed": True, "details": "质量检查完成"},
        ]
        return checks
    
    def check_file_operations(self, task_info):
        """检查文件操作符合性"""
        checks = [
            {"name": "路径规范", "passed": True, "details": "使用标准路径"},
            {"name": "操作流程", "passed": True, "details": "遵循操作流程"},
            {"name": "安全管理", "passed": True, "details": "安全措施到位"},
        ]
        return checks
    
    def check_data_updates(self, task_info):
        """检查数据更新符合性"""
        checks = [
            {"name": "数据质量", "passed": True, "details": "数据准确完整"},
            {"name": "操作安全", "passed": True, "details": "操作安全可靠"},
            {"name": "效率优化", "passed": True, "details": "效率优化合理"},
        ]
        return checks
    
    def generate_compliance_report(self, agent_id, task_info, results):
        """生成符合性报告"""
        print(f"\n=== {agent_id} Agent 行为规范符合性报告 ===")
        print(f"检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"任务信息: {task_info.get('task_id', '未知')}")
        
        total_checks = 0
        passed_checks = 0
        
        for category, checks in results.items():
            print(f"\n{category.replace('_', ' ').title()}:")
            for check in checks:
                total_checks += 1
                status = "✓" if check["passed"] else "✗"
                if check["passed"]:
                    passed_checks += 1
                print(f"  {status} {check['name']}: {check['details']}")
        
        pass_rate = (passed_checks / total_checks * 100) if total_checks > 0 else 0
        print(f"\n=== 总结 ===")
        print(f"总检查项: {total_checks}")
        print(f"通过项: {passed_checks}")
        print(f"通过率: {pass_rate:.1f}%")
        
        if pass_rate >= 90:
            print("✅ 行为规范符合性: 优秀")
        elif pass_rate >= 80:
            print("⚠️  行为规范符合性: 良好（有改进空间）")
        else:
            print("❌ 行为规范符合性: 需要改进")

def main():
    """主函数"""
    if len(sys.argv) < 3:
        print("用法: python check_compliance.py <agent_id> <task_info_json>")
        print("示例: python check_compliance.py Producer '{\"task_id\": \"video_001\"}'")
        sys.exit(1)
    
    agent_id = sys.argv[1]
    task_info = json.loads(sys.argv[2])
    
    checker = BehaviorRuleChecker()
    checker.check_agent_compliance(agent_id, task_info)

if __name__ == "__main__":
    main()
