"""
商业标识脱敏处理器

处理对象：项目名称、建设单位、总承包单位、监理单位、劳务分包单位等
执行策略：彻底泛化，替换为标准工程角色词汇
"""

import re
from typing import Any
from .base_processor import BaseDesensitizer


class BizDesensitizer(BaseDesensitizer):
    """商业标识脱敏处理器"""

    def _compile_patterns(self):
        """编译商业标识相关正则表达式"""
        # 项目标识（如"都四山地轨道交通项目DSZH标"）
        self.patterns["project"] = re.compile(
            r'([\u4e00-\u9fa5A-Z0-9\-]{5,30}(?:项目|标段|工程))'
        )

        # 建设单位（含集团、局、有限公司等）
        self.patterns["constructor"] = re.compile(
            r'([\u4e00-\u9fa5]{2,6}(?:集团|局|有限公司))'
        )

        # 总承包单位
        self.patterns["contractor"] = re.compile(
            r'(总承包单位[：:]?\s*[\u4e00-\u9fa5]{2,10}(?:集团|局|公司)?)'
        )

        # 监理单位
        self.patterns["supervisor"] = re.compile(
            r'([\u4e00-\u9fa5]{2,8}(?:监理|咨询)(?:公司|单位))'
        )

        # 设计单位
        self.patterns["designer"] = re.compile(
            r'([\u4e00-\u9fa5]{2,8}(?:设计|勘察)(?:院|所|公司))'
        )

        # 劳务分包单位
        self.patterns["subcontractor"] = re.compile(
            r'([\u4e00-\u9fa5]{2,10}(?:劳务|分包)(?:公司|单位))'
        )

        # 数字化/科技公司
        self.patterns["tech_company"] = re.compile(
            r'([\u4e00-\u9fa5]{2,8}(?:数字|科技|信息|软件)(?:公司|科技))'
        )

        # 合同编号
        self.patterns["contract_no"] = re.compile(
            r'(合同编号?[：:]?\s*[A-Z0-9\-]{5,20})'
        )

        # 统一社会信用代码/组织机构代码
        self.patterns["credit_code"] = re.compile(
            r'([A-Z0-9]{18})'  # 18位统一社会信用代码
        )

    def process(self, content: str, registry: Any, strict_mode: bool = False) -> str:
        """执行商业标识脱敏"""
        # 1. 总承包单位泛化（必须在项目标识之前处理，防止"工程"被项目模式破坏）
        def replace_contractor(match):
            return "[总承包单位]"

        content = self.patterns["contractor"].sub(replace_contractor, content)

        # 补充匹配：行首或换行后的"总承包单位"（没有冒号的情况）
        content = re.sub(
            r'([，。；\n]|^)(总承包单位)[：:\s]*([\u4e00-\u9fa5]{2,10}(?:集团|局|公司))',
            r'\1[\2]',
            content
        )

        # 2. 项目标识泛化（必须在总承包单位之后处理）
        def replace_project(match):
            original = match.group(1)
            placeholder = "[某工程项目]"
            registry.register_company(original, "项目")
            return placeholder

        content = self.patterns["project"].sub(replace_project, content)

        # 3. 建设单位泛化
        def replace_constructor(match):
            original = match.group(1)
            placeholder = registry.register_company(original, "建设")
            return placeholder

        content = self.patterns["constructor"].sub(replace_constructor, content)

        # 4. 监理单位泛化
        def replace_supervisor(match):
            original = match.group(1)
            placeholder = registry.register_company(original, "监理")
            return placeholder

        content = self.patterns["supervisor"].sub(replace_supervisor, content)

        # 5. 设计单位泛化
        def replace_designer(match):
            original = match.group(1)
            placeholder = registry.register_company(original, "设计")
            return placeholder

        content = self.patterns["designer"].sub(replace_designer, content)

        # 6. 劳务分包单位泛化
        def replace_subcontractor(match):
            original = match.group(1)
            placeholder = registry.register_company(original, "劳务")
            return placeholder

        content = self.patterns["subcontractor"].sub(replace_subcontractor, content)

        # 7. 数字化/科技公司泛化
        def replace_tech(match):
            original = match.group(1)
            placeholder = registry.register_company(original, "数字化")
            return placeholder

        content = self.patterns["tech_company"].sub(replace_tech, content)

        # 8. 合同编号掩码
        content = self.patterns["contract_no"].sub("[合同编号脱敏]", content)

        # 9. 统一社会信用代码掩码
        content = self.patterns["credit_code"].sub("[信用代码脱敏]", content)

        return content

    def extract_companies(self, content: str) -> list:
        """提取所有企业/单位名称"""
        companies = []

        patterns = [
            ("project", self.patterns["project"]),
            ("constructor", self.patterns["constructor"]),
            ("supervisor", self.patterns["supervisor"]),
            ("designer", self.patterns["designer"]),
            ("subcontractor", self.patterns["subcontractor"]),
        ]

        for company_type, pattern in patterns:
            for match in pattern.finditer(content):
                companies.append({
                    "name": match.group(1),
                    "type": company_type,
                    "position": match.span()
                })

        return companies
