"""
JoySpace 报告数据勾稽校验（借鉴 report-data-validation skill）。

能力：
- validate_report_data: 对 JoySpace 经营分析报告做7维数据勾稽校验
  1. 行列加和一致性 2. 比率合理性 3. 文字表格一致性 4. 前后数据一致性
  5. 单位正确性 6. 口径标注完整性 7. 错别字语法

与 verify_content_integrity(结构校验) 互补: 后者查 block_count/text/table 格式,
本 action 查数据数值正确性(勾稽关系)。校验清单见 references/report-validation-checklist.md
"""

import json
import re
from pathlib import Path

# 严重程度
SEVERITY_CRITICAL = "critical"  # 🔴 严重: 数据矛盾必改
SEVERITY_MEDIUM = "medium"      # 🟡 中等: 可能错误需核实
SEVERITY_MINOR = "minor"        # 🟢 轻微: 四舍五入等可忽略
SEVERITY_TEXT = "text"          # 🔵 文字: 错别字/语法


def _extract_structure(text: str) -> dict:
    """识别报告结构标记: TOPIC/HIGHLIGHT/FOLDABLE/TABLE/COLUMN"""
    topics = re.findall(r'=====\s*TOPIC:\s*(\w+)\s*=====', text)
    highlights = re.findall(r'\[HIGHLIGHT:\s*([^\]]+)\]', text)
    foldables = re.findall(r'\[FOLDABLE:\s*([^\]]+)\]', text)
    # 表格块
    tables = []
    table_blocks = re.findall(r'---\s*TABLE\s*---\n(.*?)\n---\s*END TABLE\s*---', text, re.S)
    for tb in table_blocks:
        rows = [r.strip().split("|") for r in tb.strip().split("\n") if r.strip()]
        tables.append(rows)
    return {
        "topics": topics, "highlights": highlights, "foldables": foldables,
        "tables": tables, "topic_count": len(topics), "table_count": len(tables),
    }


def _extract_numbers(text: str) -> list:
    """提取文本中的所有数值(含单位)"""
    # 匹配 3,598亿 / 41.7% / 717.2万元 / -10.2% 等
    pattern = r'(-?\d[\d,]*\.?\d*)\s*(亿|万|百万|千万|%|亿元|万元|百万元)?'
    return re.findall(pattern, text)


def _check_row_col_sum(tables: list) -> list:
    """维度1: 行列加和一致性"""
    issues = []
    for i, table in enumerate(tables):
        if len(table) < 3:
            continue
        # 找合计行(含"合计"/"总计"/"Total")
        for r, row in enumerate(table):
            row_str = "".join(row)
            if re.search(r'合计|总计|Total|小计', row_str):
                # 检查数值列加和
                for c in range(1, len(row)):
                    try:
                        cells = [float(table[rr][c].replace(",", "").replace("%","").replace("亿","").replace("万",""))
                                 for rr in range(1, r) if rr < len(table) and c < len(table[rr])
                                 if table[rr][c].strip() and re.match(r'-?[\d,]+\.?\d*', table[rr][c].strip())]
                        if cells:
                            s = sum(cells)
                            total_str = row[c].replace(",", "").replace("%","").replace("亿","").replace("万","")
                            total = float(total_str) if re.match(r'-?[\d,]+\.?\d*', total_str) else None
                            if total is not None and abs(s - total) > 0.1:
                                issues.append({"dimension": "行列加和", "severity": SEVERITY_MEDIUM,
                                    "location": f"表{i+1}行{r+1}列{c+1}",
                                    "detail": f"分项加和{s} ≠ 合计{total}, 差{abs(s-total):.2f}"})
                    except (ValueError, IndexError):
                        continue
    return issues


def _check_ratio_reasonability(text: str, highlights: list) -> list:
    """维度2: 比率合理性"""
    issues = []
    # 检查"增长X亿"vs收入规模(绝对值vs百分比混淆)
    for m in re.finditer(r'增长\s*(-?\d[\d,]*\.?\d*)\s*(亿|万|百万|%)\s*', text):
        val, unit = m.group(1), m.group(2)
        try:
            v = float(val.replace(",", ""))
            if unit == "%" and v > 100:
                issues.append({"dimension": "比率合理性", "severity": SEVERITY_CRITICAL,
                    "location": m.group(0),
                    "detail": f"增速{v}%异常(>100%), 可能是绝对值误写百分比"})
            if unit in ("亿", "万", "百万") and v > 1000:
                issues.append({"dimension": "比率合理性", "severity": SEVERITY_MEDIUM,
                    "location": m.group(0),
                    "detail": f"增长{v}{unit}绝对值过大, 确认是否应为{v}%"})
        except ValueError:
            continue
    return issues


def _check_text_table_consistency(text: str, tables: list, highlights: list) -> list:
    """维度3: 文字与表格一致性"""
    issues = []
    # 提取HIGHLIGHT中的数值, 检查是否在某个表格里出现
    for hl in highlights:
        hl_numbers = re.findall(r'(-?\d[\d,]*\.?\d*)\s*(亿|万|百万|%)', hl)
        for val, unit in hl_numbers:
            # 在表格数据里找这个值
            found = False
            for table in tables:
                table_str = json.dumps(table, ensure_ascii=False)
                if val in table_str:
                    found = True; break
            if not found and val not in ("0", "1", "2"):  # 忽略小数值
                issues.append({"dimension": "文字表格一致性", "severity": SEVERITY_MEDIUM,
                    "location": f"HIGHLIGHT: {hl[:30]}",
                    "detail": f"数值{val}{unit}在HIGHLIGHT但未在表格中找到, 可能不一致"})
    return issues


def _check_unit_correctness(text: str) -> list:
    """维度5: 单位正确性"""
    issues = []
    # 检查"X亿"是否应为"X万"(省区级收入通常万级别)
    for m in re.finditer(r'(\d[\d,]*\.?\d*)\s*亿', text):
        val = float(m.group(1).replace(",", ""))
        # 省区/区域/部门级数据若>100亿可能单位错
        context = text[max(0, m.start()-20):m.start()]
        if re.search(r'省区|区域|部门|网点|门店', context) and val > 100:
            issues.append({"dimension": "单位正确性", "severity": SEVERITY_MEDIUM,
                "location": m.group(0),
                "detail": f"省区级数据{val}亿过大, 确认是否应为{val}万"})
    return issues


def _check_typo(text: str) -> list:
    """维度7: 错别字语法(基础检查)"""
    issues = []
    # 常见错别字
    typos = {"登陆": "登录", "帐号": "账号", "帐户": "账户", "链接": "链接",
             "做帐": "做账", "查帐": "查账", "记帐": "记账",
             "赢利": "盈利", "营利": "盈利"}
    for wrong, right in typos.items():
        if wrong in text:
            count = text.count(wrong)
            issues.append({"dimension": "错别字", "severity": SEVERITY_TEXT,
                "location": wrong, "detail": f"发现'{wrong}'{count}处, 应为'{right}'"})
    return issues


def validate_report_data(client, params: dict) -> dict:
    """对 JoySpace 报告做7维数据勾稽校验(借鉴report-data-validation)。

    params:
        page_id: 文档页面ID(必填) 或 text: 直接传入报告文本
        team_id: 团队ID(可选)
    返回: {issues: [...], summary, structure}
    """
    text = params.get("text")
    page_id = params.get("page_id") or params.get("pageId")
    if not text and page_id:
        # 读取文档内容
        print(f"[报告校验] 读取文档 pageId={page_id}")
        from api import document
        result = document.get_page_basic_info(client, {"page_id": page_id,
                                                       "team_id": params.get("team_id") or client._team_id})
        # 提取文本(从page内容)
        text = result.get("content") or result.get("markdown") or json.dumps(result, ensure_ascii=False)
    if not text:
        raise RuntimeError("请指定 page_id 或 text")

    print(f"[报告校验] 文本长度: {len(text)}")

    # 1. 识别报告结构
    structure = _extract_structure(text)
    print(f"  结构: {structure['topic_count']}个TOPIC, {structure['table_count']}个表格, "
          f"{len(structure['highlights'])}个HIGHLIGHT")

    # 2. 7维校验
    all_issues = []
    all_issues.extend(_check_row_col_sum(structure["tables"]))
    all_issues.extend(_check_ratio_reasonability(text, structure["highlights"]))
    all_issues.extend(_check_text_table_consistency(text, structure["tables"], structure["highlights"]))
    all_issues.extend(_check_unit_correctness(text))
    all_issues.extend(_check_typo(text))

    # 维度4(前后一致性)/6(口径标注)需要AI语义判断,这里只做基础数值重复检测
    # 维度4: 同一数值多次出现的上下文
    numbers = _extract_numbers(text)
    num_counts = {}
    for val, unit in numbers:
        key = f"{val}{unit}"
        num_counts[key] = num_counts.get(key, 0) + 1
    # (基础检测完成,深度前后一致性和口径标注由AI按checklist.md判断)

    # 3. 生成校验报告
    severity_count = {"critical": 0, "medium": 0, "minor": 0, "text": 0}
    for iss in all_issues:
        severity_count[iss["severity"]] = severity_count.get(iss["severity"], 0) + 1

    print(f"\n  校验完成: 🔴严重{severity_count['critical']} 🟡中等{severity_count['medium']} "
          f"🟢轻微{severity_count['minor']} 🔵文字{severity_count['text']}")

    return {
        "issues": all_issues,
        "issue_count": len(all_issues),
        "severity_count": severity_count,
        "structure": structure,
        "note": "维度4(前后一致性)/维度6(口径标注)需AI按 references/report-validation-checklist.md 深度判断",
    }
