#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
流程规划专家 - 基于华为系方法论与APQC框架
生成企业L1-L3流程架构及能力热力图
"""

import json
import os
from datetime import datetime
from typing import Dict, List, Any, Optional

# ============ APQC 参考框架数据 ============

APQC_OPERATING_PROCESSES = {
    "1.0": {"name": "制定愿景与战略", "description": "定义企业战略方向和目标"},
    "2.0": {"name": "开发与管理产品/服务", "description": "产品全生命周期管理"},
    "3.0": {"name": "市场营销与销售", "description": "市场拓展与客户获取"},
    "4.0": {"name": "交付产品/服务", "description": "订单履行与服务交付"},
    "5.0": {"name": "管理客户服务", "description": "客户满意度与售后服务"}
}

APQC_SUPPORT_PROCESSES = {
    "6.0": {"name": "开发和管理人力资本", "description": "人才管理与组织发展"},
    "7.0": {"name": "管理信息技术", "description": "IT规划与系统建设"},
    "8.0": {"name": "管理财务资源", "description": "财务规划与资金管理"},
    "9.0": {"name": "获取构建管理资产", "description": "资产管理与采购"},
    "10.0": {"name": "管理风险合规", "description": "风控与合规管理"},
    "11.0": {"name": "管理外部关系", "description": "供应商与合作伙伴管理"},
    "12.0": {"name": "开发管理能力", "description": "组织能力体系建设"}
}

# ============ 行业流程模板 ============

INDUSTRY_TEMPLATES = {
    "制造业": {
        "operating": {
            "L1-O1": {
                "name": "集成产品开发(IPD)",
                "description": "从需求到产品上市的全流程",
                "L2": {
                    "L2-O1-1": {"name": "需求管理", "L3": ["市场需求收集", "需求分析与排序", "需求变更管理"]},
                    "L2-O1-2": {"name": "产品规划", "L3": ["产品路标规划", "Charter开发", "投资决策评审"]},
                    "L2-O1-3": {"name": "技术开发", "L3": ["技术预研", "平台开发", "技术迁移"]},
                    "L2-O1-4": {"name": "产品开发", "L3": ["概念阶段", "计划阶段", "开发验证", "发布阶段"]},
                    "L2-O1-5": {"name": "生命周期管理", "L3": ["上市管理", "产品运营", "退市管理"]}
                }
            },
            "L1-O2": {
                "name": "线索到回款(LTC)",
                "description": "从市场线索到合同回款的全流程",
                "L2": {
                    "L2-O2-1": {"name": "线索管理", "L3": ["线索收集", "线索验证", "线索培育"]},
                    "L2-O2-2": {"name": "机会点管理", "L3": ["机会点识别", "机会点评估", "投标决策"]},
                    "L2-O2-3": {"name": "合同管理", "L3": ["合同谈判", "合同评审", "合同签订"]},
                    "L2-O2-4": {"name": "订单履行", "L3": ["订单处理", "生产排程", "交付管理", "开票收款"]}
                }
            },
            "L1-O3": {
                "name": "问题到解决(ITR)",
                "description": "客户问题处理与闭环管理",
                "L2": {
                    "L2-O3-1": {"name": "问题受理", "L3": ["问题登记", "问题分级", "问题分派"]},
                    "L2-O3-2": {"name": "问题处理", "L3": ["问题诊断", "方案制定", "问题解决"]},
                    "L2-O3-3": {"name": "满意度管理", "L3": ["回访确认", "满意度调查", "改进闭环"]}
                }
            }
        },
        "enabling": {
            "L1-E1": {
                "name": "战略到执行",
                "description": "战略解码与执行监控",
                "L2": {
                    "L2-E1-1": {"name": "战略解码", "L3": ["战略分析", "目标分解", "关键任务识别"]},
                    "L2-E1-2": {"name": "执行监控", "L3": ["经营分析", "绩效监控", "战略复盘"]}
                }
            },
            "L1-E2": {
                "name": "供应链管理",
                "description": "端到端供应链协同",
                "L2": {
                    "L2-E2-1": {"name": "计划管理", "L3": ["需求计划", "供应计划", "产销协同"]},
                    "L2-E2-2": {"name": "采购管理", "L3": ["供应商管理", "采购执行", "采购结算"]},
                    "L2-E2-3": {"name": "制造管理", "L3": ["生产计划", "生产执行", "质量管理"]},
                    "L2-E2-4": {"name": "物流管理", "L3": ["仓储管理", "运输配送", "库存管理"]}
                }
            }
        },
        "supporting": {
            "L1-S1": {
                "name": "人力资源管理",
                "description": "人才选育用留全流程",
                "L2": {
                    "L2-S1-1": {"name": "组织管理", "L3": ["组织设计", "岗位管理", "编制管理"]},
                    "L2-S1-2": {"name": "人才获取", "L3": ["招聘管理", "入职管理", "人才调配"]},
                    "L2-S1-3": {"name": "人才发展", "L3": ["培训管理", "绩效管理", "职业发展"]},
                    "L2-S1-4": {"name": "薪酬福利", "L3": ["薪酬管理", "福利管理", "激励管理"]}
                }
            },
            "L1-S2": {
                "name": "财经管理",
                "description": "财务规划与运营管理",
                "L2": {
                    "L2-S2-1": {"name": "财务规划", "L3": ["预算管理", "资金规划", "投融资管理"]},
                    "L2-S2-2": {"name": "财务运营", "L3": ["会计核算", "税务管理", "报表管理"]},
                    "L2-S2-3": {"name": "财务控制", "L3": ["成本管理", "费用控制", "内控审计"]}
                }
            },
            "L1-S3": {
                "name": "IT管理",
                "description": "信息化建设与运维",
                "L2": {
                    "L2-S3-1": {"name": "IT规划", "L3": ["架构规划", "系统规划", "投资规划"]},
                    "L2-S3-2": {"name": "IT建设", "L3": ["需求管理", "开发实施", "上线交付"]},
                    "L2-S3-3": {"name": "IT运维", "L3": ["系统运维", "数据管理", "安全管理"]}
                }
            }
        }
    },
    
    "互联网/科技": {
        "operating": {
            "L1-O1": {
                "name": "产品管理",
                "description": "互联网产品全生命周期管理",
                "L2": {
                    "L2-O1-1": {"name": "用户研究", "L3": ["用户调研", "用户画像", "需求分析"]},
                    "L2-O1-2": {"name": "产品规划", "L3": ["产品战略", "版本规划", "路线图管理"]},
                    "L2-O1-3": {"name": "产品设计", "L3": ["原型设计", "交互设计", "视觉设计"]},
                    "L2-O1-4": {"name": "产品运营", "L3": ["上线运营", "数据分析", "迭代优化"]}
                }
            },
            "L1-O2": {
                "name": "技术研发",
                "description": "软件研发与技术创新",
                "L2": {
                    "L2-O2-1": {"name": "技术规划", "L3": ["技术战略", "架构设计", "技术选型"]},
                    "L2-O2-2": {"name": "敏捷开发", "L3": ["迭代规划", "开发实施", "代码评审"]},
                    "L2-O2-3": {"name": "质量保障", "L3": ["测试管理", "自动化测试", "性能优化"]},
                    "L2-O2-4": {"name": "发布交付", "L3": ["持续集成", "发布管理", "灰度发布"]}
                }
            },
            "L1-O3": {
                "name": "用户增长",
                "description": "用户获取与留存运营",
                "L2": {
                    "L2-O3-1": {"name": "获客运营", "L3": ["渠道投放", "内容营销", "SEO/SEM"]},
                    "L2-O3-2": {"name": "激活转化", "L3": ["新客引导", "转化优化", "A/B测试"]},
                    "L2-O3-3": {"name": "留存变现", "L3": ["用户分层", "会员体系", "商业化运营"]}
                }
            }
        },
        "enabling": {
            "L1-E1": {
                "name": "数据智能",
                "description": "数据驱动决策支持",
                "L2": {
                    "L2-E1-1": {"name": "数据治理", "L3": ["数据标准", "数据质量", "主数据管理"]},
                    "L2-E1-2": {"name": "数据分析", "L3": ["指标体系", "BI报表", "数据挖掘"]},
                    "L2-E1-3": {"name": "AI应用", "L3": ["算法模型", "智能推荐", "智能客服"]}
                }
            },
            "L1-E2": {
                "name": "平台运营",
                "description": "技术平台与生态运营",
                "L2": {
                    "L2-E2-1": {"name": "云服务", "L3": ["云资源管理", "容器编排", "弹性伸缩"]},
                    "L2-E2-2": {"name": "安全合规", "L3": ["安全策略", "隐私保护", "合规审计"]}
                }
            }
        },
        "supporting": {
            "L1-S1": {"name": "人力资源管理", "L2": {}},
            "L1-S2": {"name": "财经管理", "L2": {}},
            "L1-S3": {"name": "行政管理", "L2": {}}
        }
    },
    
    "服务业": {
        "operating": {
            "L1-O1": {
                "name": "客户服务交付",
                "description": "核心服务交付流程",
                "L2": {
                    "L2-O1-1": {"name": "服务设计", "L3": ["服务蓝图", "服务标准", "SLA定义"]},
                    "L2-O1-2": {"name": "服务请求", "L3": ["需求受理", "服务分派", "资源调度"]},
                    "L2-O1-3": {"name": "服务执行", "L3": ["服务实施", "质量监控", "服务交付"]},
                    "L2-O1-4": {"name": "服务评价", "L3": ["满意度调查", "服务改进", "知识沉淀"]}
                }
            },
            "L1-O2": {
                "name": "客户关系管理",
                "description": "客户全生命周期管理",
                "L2": {
                    "L2-O2-1": {"name": "客户获取", "L3": ["市场拓展", "商机挖掘", "签约转化"]},
                    "L2-O2-2": {"name": "客户经营", "L3": ["客户分层", "客户关怀", "增值服务"]},
                    "L2-O2-3": {"name": "客户挽留", "L3": ["流失预警", "挽留策略", "投诉处理"]}
                }
            }
        },
        "enabling": {
            "L1-E1": {"name": "资源管理", "L2": {}},
            "L1-E2": {"name": "合作伙伴管理", "L2": {}}
        },
        "supporting": {
            "L1-S1": {"name": "人力资源管理", "L2": {}},
            "L1-S2": {"name": "财经管理", "L2": {}},
            "L1-S3": {"name": "品牌管理", "L2": {}}
        }
    }
}

# 默认通用模板
DEFAULT_TEMPLATE = INDUSTRY_TEMPLATES["制造业"]

# ============ 流程规划核心类 ============

class ProcessPlanningExpert:
    """流程规划专家 - 生成企业流程架构"""
    
    def __init__(self):
        self.company_info = {}
        self.process_architecture = {}
        self.capability_matrix = []
    
    def collect_inputs(self, 
                      company_name: str,
                      industry: str,
                      vision: str,
                      strategy: str,
                      scale: str = "中型",
                      pain_points: List[str] = None) -> Dict:
        """收集企业战略输入"""
        self.company_info = {
            "name": company_name,
            "industry": industry,
            "vision": vision,
            "strategy": strategy,
            "scale": scale,
            "pain_points": pain_points or [],
            "planning_date": datetime.now().strftime("%Y-%m-%d")
        }
        return self.company_info
    
    def generate_architecture(self) -> Dict:
        """生成L1-L3流程架构"""
        industry = self.company_info.get("industry", "制造业")
        
        # 选择行业模板
        template = INDUSTRY_TEMPLATES.get(industry, DEFAULT_TEMPLATE)
        
        # 构建完整架构
        architecture = {
            "company": self.company_info,
            "framework": "OES分类法（华为系）",
            "reference": "APQC PCF 7.0",
            "L1_processes": [],
            "total_L2": 0,
            "total_L3": 0
        }
        
        l2_count = 0
        l3_count = 0
        
        # 运营类流程
        for code, data in template.get("operating", {}).items():
            l1_process = {
                "code": code,
                "name": data["name"],
                "category": "运营类(Operating)",
                "description": data["description"],
                "L2_count": len(data.get("L2", {})),
                "L2_processes": []
            }
            
            for l2_code, l2_data in data.get("L2", {}).items():
                l2_process = {
                    "code": l2_code,
                    "name": l2_data["name"],
                    "L3_count": len(l2_data.get("L3", [])),
                    "L3_processes": l2_data.get("L3", [])
                }
                l1_process["L2_processes"].append(l2_process)
                l2_count += 1
                l3_count += len(l2_data.get("L3", []))
            
            architecture["L1_processes"].append(l1_process)
        
        # 使能类流程
        for code, data in template.get("enabling", {}).items():
            l1_process = {
                "code": code,
                "name": data["name"],
                "category": "使能类(Enabling)",
                "description": data.get("description", ""),
                "L2_count": len(data.get("L2", {})),
                "L2_processes": []
            }
            
            for l2_code, l2_data in data.get("L2", {}).items():
                l2_process = {
                    "code": l2_code,
                    "name": l2_data["name"],
                    "L3_count": len(l2_data.get("L3", [])),
                    "L3_processes": l2_data.get("L3", [])
                }
                l1_process["L2_processes"].append(l2_process)
                l2_count += 1
                l3_count += len(l2_data.get("L3", []))
            
            architecture["L1_processes"].append(l1_process)
        
        # 支撑类流程
        for code, data in template.get("supporting", {}).items():
            l1_process = {
                "code": code,
                "name": data["name"],
                "category": "支撑类(Supporting)",
                "description": data.get("description", ""),
                "L2_count": len(data.get("L2", {})),
                "L2_processes": []
            }
            
            for l2_code, l2_data in data.get("L2", {}).items():
                l2_process = {
                    "code": l2_code,
                    "name": l2_data["name"],
                    "L3_count": len(l2_data.get("L3", [])),
                    "L3_processes": l2_data.get("L3", [])
                }
                l1_process["L2_processes"].append(l2_process)
                l2_count += 1
                l3_count += len(l2_data.get("L3", []))
            
            architecture["L1_processes"].append(l1_process)
        
        architecture["total_L2"] = l2_count
        architecture["total_L3"] = l3_count
        architecture["L1_count"] = len(architecture["L1_processes"])
        
        self.process_architecture = architecture
        return architecture
    
    def generate_capability_matrix(self) -> List[Dict]:
        """生成能力评估矩阵（用于热力图）"""
        matrix = []
        
        # 为每个L1流程生成熟度评估
        for l1 in self.process_architecture.get("L1_processes", []):
            # 根据类别确定战略重要性
            if l1["category"] == "运营类(Operating)":
                importance = "高"
                importance_score = 3
            elif l1["category"] == "使能类(Enabling)":
                importance = "中"
                importance_score = 2
            else:
                importance = "中"
                importance_score = 2
            
            # 模拟当前成熟度（实际应由用户输入）
            maturity_options = ["低", "中", "高"]
            maturity = maturity_options[hash(l1["code"]) % 3]
            maturity_score = {"低": 1, "中": 2, "高": 3}[maturity]
            
            # 计算优先级
            gap = importance_score - maturity_score
            if gap > 0:
                priority = "高"
            elif gap == 0:
                priority = "中"
            else:
                priority = "低"
            
            matrix.append({
                "L1_code": l1["code"],
                "L1_name": l1["name"],
                "category": l1["category"],
                "importance": importance,
                "importance_score": importance_score,
                "maturity": maturity,
                "maturity_score": maturity_score,
                "priority": priority,
                "gap": gap,
                "L2_count": l1["L2_count"],
                "L3_count": sum(l2["L3_count"] for l2 in l1["L2_processes"])
            })
        
        self.capability_matrix = matrix
        return matrix
    
    def generate_roadmap(self) -> List[Dict]:
        """生成流程建设路线图"""
        roadmap = []
        
        # 按优先级排序
        sorted_matrix = sorted(
            self.capability_matrix, 
            key=lambda x: (x["priority"] != "高", x["priority"] != "中", x["gap"]),
            reverse=True
        )
        
        phases = {
            "phase1": {"name": "第一阶段（0-6个月）", "focus": "高优先级流程", "items": []},
            "phase2": {"name": "第二阶段（6-12个月）", "focus": "中优先级流程", "items": []},
            "phase3": {"name": "第三阶段（12-18个月）", "focus": "基础能力建设", "items": []}
        }
        
        for item in sorted_matrix:
            if item["priority"] == "高":
                phases["phase1"]["items"].append(item)
            elif item["priority"] == "中":
                phases["phase2"]["items"].append(item)
            else:
                phases["phase3"]["items"].append(item)
        
        return phases
    
    def export_to_json(self, filepath: str):
        """导出架构数据到JSON"""
        output = {
            "company_info": self.company_info,
            "process_architecture": self.process_architecture,
            "capability_matrix": self.capability_matrix,
            "roadmap": self.generate_roadmap()
        }
        
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(output, f, ensure_ascii=False, indent=2)
        
        return filepath


# ============ 主函数 ============

def generate_process_planning(
    company_name: str,
    industry: str,
    vision: str,
    strategy: str,
    scale: str = "中型",
    pain_points: List[str] = None,
    output_dir: str = None
) -> Dict:
    """
    主函数：生成完整的流程规划方案
    
    Args:
        company_name: 公司名称
        industry: 行业（制造业/互联网/科技/服务业等）
        vision: 企业愿景
        strategy: 战略目标
        scale: 企业规模（小型/中型/大型）
        pain_points: 业务痛点列表
        output_dir: 输出目录
    
    Returns:
        包含架构数据、能力矩阵、路线图的字典
    """
    expert = ProcessPlanningExpert()
    
    # 收集输入
    expert.collect_inputs(
        company_name=company_name,
        industry=industry,
        vision=vision,
        strategy=strategy,
        scale=scale,
        pain_points=pain_points
    )
    
    # 生成架构
    architecture = expert.generate_architecture()
    
    # 生成熟度矩阵
    capability_matrix = expert.generate_capability_matrix()
    
    # 生成路线图
    roadmap = expert.generate_roadmap()
    
    # 导出JSON
    if output_dir:
        os.makedirs(output_dir, exist_ok=True)
        json_path = os.path.join(output_dir, "process_architecture.json")
        expert.export_to_json(json_path)
    
    return {
        "company_info": expert.company_info,
        "architecture": architecture,
        "capability_matrix": capability_matrix,
        "roadmap": roadmap
    }


if __name__ == "__main__":
    # 测试示例
    result = generate_process_planning(
        company_name="示例科技有限公司",
        industry="制造业",
        vision="成为行业领先的智能制造企业",
        strategy="未来3年实现数字化转型，提升运营效率30%",
        scale="中型",
        pain_points=["流程割裂", "信息孤岛", "响应速度慢"],
        output_dir="./output"
    )
    
    print(f"流程架构已生成：")
    print(f"- L1流程数：{result['architecture']['L1_count']}")
    print(f"- L2流程组数：{result['architecture']['total_L2']}")
    print(f"- L3流程数：{result['architecture']['total_L3']}")
