# -*- coding: utf-8 -*-
"""
需求编号生成与提取工具。
"""

import re
from typing import Optional, Tuple, Dict


class RequirementIDGenerator:
    def __init__(self, type_prefix: Dict[str, str]):
        self.type_prefix = type_prefix

    def normalize(self, req_id: str) -> str:
        if not req_id:
            return ""
        return str(req_id).strip()

    def extract_from_text(self, text: str) -> Tuple[Optional[str], str]:
        if not text:
            return None, text

        pattern1 = r"^\s*([A-Za-z]{2,10}[-_]\d+(?:[-.\d]+)*)\s*[:：\)\]】]?\s*(.+)$"
        match = re.match(pattern1, text)
        if match:
            return match.group(1).strip(), match.group(2).strip()

        pattern2 = r"^\s*([A-Za-z]\d+)\s*[:：\)\]】]?\s*(.+)$"
        match = re.match(pattern2, text)
        if match:
            return match.group(1).strip(), match.group(2).strip()

        pattern3 = r"^\s*([a-z0-9]{1,2}[\)）])\s*(.+)$"
        match = re.match(pattern3, text)
        if match:
            code = match.group(1).strip().rstrip(")）")
            return code, match.group(2).strip()

        return None, text

    def generate(
        self,
        req_type: str,
        section_number: str,
        index: int,
        doc_req_id: str = "",
        parent_req_id: str = "",
        split_index: int = 1,
        split_total: int = 1,
    ) -> str:
        base_id = self._generate_base(req_type, section_number, index, doc_req_id, parent_req_id)
        if split_total > 1:
            return f"{base_id}-S{split_index}"
        return base_id

    def _generate_base(
        self,
        req_type: str,
        section_number: str,
        index: int,
        doc_req_id: str,
        parent_req_id: str,
    ) -> str:
        if doc_req_id:
            complete_id_pattern = r"^[A-Za-z0-9]{2,10}[-_].+$"
            if re.match(complete_id_pattern, doc_req_id):
                return doc_req_id.replace("_", "-")

        if doc_req_id and parent_req_id:
            return f"{parent_req_id}-{doc_req_id}"

        prefix = self.type_prefix.get(req_type, "FR")
        section_part = section_number if section_number else "NA"
        return f"{prefix}-{section_part}-{index}"
