from __future__ import annotations

import re


TRAVEL_GRADE_KEYS = tuple(f"P{level}" for level in range(9))


def resolve_travel_policy_grade_key(grade: str | None) -> str | None:
    normalized = str(grade or "").strip().upper()
    if not normalized:
        return None

    if "董事会" in normalized:
        return "P8"

    p_match = re.search(r"P\s*([0-8])", normalized)
    if p_match:
        return f"P{int(p_match.group(1))}"

    level_match = re.search(r"(?<!\d)([0-8])\s*级", normalized)
    if level_match:
        return f"P{int(level_match.group(1))}"

    m_match = re.search(r"M\s*(\d+)", normalized)
    if m_match:
        level = int(m_match.group(1))
        if level <= 1:
            return "P5"
        if level <= 2:
            return "P6"
        return "P7"

    if normalized.startswith("D"):
        return "P8"

    if any(keyword in normalized for keyword in ("外聘专家", "专家")):
        return "P6"
    if "高层经理" in normalized or "公司级" in normalized:
        return "P7"
    if "中层经理" in normalized:
        return "P6"
    if "基层经理" in normalized:
        return "P5"
    if "主管" in normalized or "资深" in normalized:
        return "P4"

    return None


def travel_policy_grade_key_candidates(grade_key: str | None) -> list[str]:
    raw_key = str(grade_key or "").strip()
    normalized = raw_key.upper()
    if not normalized:
        return []

    candidates = [normalized]
    legacy_key = raw_key.lower()
    if legacy_key in {"junior", "mid", "senior", "manager", "executive"}:
        candidates.append(legacy_key)
    legacy = _legacy_grade_band(normalized)
    if legacy and legacy not in candidates:
        candidates.append(legacy)
    return candidates


def _legacy_grade_band(grade_key: str) -> str:
    match = re.fullmatch(r"P([0-8])", grade_key)
    if not match:
        return ""
    level = int(match.group(1))
    if level <= 3:
        return "junior"
    if level <= 5:
        return "mid"
    if level <= 7:
        return "senior"
    return "executive"
