from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Iterable


@dataclass(frozen=True)
class ColumnRole:
    role: str
    confidence: float
    reasons: tuple[str, ...] = ()


STATUS_TOKENS = ("状态", "亮灯", "灯", "风险", "预警", "判断", "status", "flag", "risk")
STATUS_MARKERS = ("✔", "✖", "√", "×", "✅", "❌", "🟢", "🟡", "🔴", "[status:")
RANK_TOKENS = ("序号", "编号", "排名", "名次", "排行", "rank", "ranking")
DATE_TOKENS = ("日期", "时间", "周期", "月份", "季度", "年份", "date", "time", "period", "month", "year")
METRIC_TOKENS = (
    "率", "同比", "环比", "目标", "实际", "本期", "金额", "收入", "成本", "利润",
    "预算", "差距", "缺口", "增量", "增速", "增长", "贡献", "数量", "个数", "数",
    "达成", "完成", "预测", "占比", "绝对值", "rate", "actual", "target", "gap",
    "cost", "revenue", "profit", "amount", "metric",
)
LONG_TEXT_TOKENS = (
    "说明", "备注", "原因", "因素", "拆解", "动作", "措施", "结论", "策略", "建议",
    "口径", "描述", "明细", "详情", "内容", "方案", "摘要", "note", "remark",
    "reason", "action", "description", "strategy", "detail", "summary",
)
DIMENSION_TOKENS = (
    "等级", "级别", "层级", "类别", "分类", "类型", "分组", "档位",
    "level", "tier", "type", "category", "class", "group",
)
NAME_TOKENS = (
    "名称", "姓名", "对象", "主体", "客户", "商家", "商品", "门店", "项目", "任务",
    "团队", "部门", "省区", "区域", "地区", "城市", "片区", "网点", "负责人",
    "owner", "name", "region", "area", "team", "department", "project",
)
GENERIC_VALUE_LABELS = ("数值", "值", "结果", "口径值", "value")
PROSE_HINT_RE = re.compile(r"[，。；、]|建议|原因|说明|备注|节省|观察|转后|转按量|转包月|折算|按量|包月")
VALUE_HINT_RE = re.compile(r"(?:[¥￥]|,|%|pp|元|人|名|天|/月|\d)", re.I)


def display_units(text: str) -> int:
    total = 0
    for char in str(text):
        if ord(char) > 127:
            total += 2
        elif char.isspace():
            total += 1
        else:
            total += 1
    return total


def visual_lines(text: str) -> list[str]:
    lines = [line.strip() for line in str(text or "").splitlines()]
    return [line for line in lines if line] or [""]


def longest_display_units(text: str) -> int:
    return max((display_units(line) for line in visual_lines(text)), default=0)


def visual_char_width(char: str) -> float:
    code = ord(char)
    if char.isspace():
        return 4.0
    if char in "，。、；：？！《》【】（）“”‘'":
        return 8.0
    if code > 127:
        return 14.0
    if char.isdigit():
        return 7.5
    if "A" <= char <= "Z":
        return 8.4
    if "a" <= char <= "z":
        return 7.0
    if char in "%+-=<>/\\|":
        return 6.6
    if char in ".,;:!?()[]{}'\"`":
        return 4.8
    return 6.0


def _truncate_by_display_units(text: str, cap_units: int | None) -> str:
    if cap_units is None:
        return text
    total = 0
    chars: list[str] = []
    for char in text:
        total += 2 if ord(char) > 127 else 1
        if total > cap_units:
            break
        chars.append(char)
    return "".join(chars)


def estimated_raw_text_width(text: str, *, cap_units: int | None = 80) -> int:
    widths = []
    for line in visual_lines(text):
        sampled = _truncate_by_display_units(line, cap_units)
        widths.append(sum(visual_char_width(char) for char in sampled))
    return int(round(max(widths or [0])))


def estimated_text_width(
    text: str,
    *,
    cap_units: int | None = 80,
    padding: int = 24,
    buffer: int = 18,
    buffer_ratio: float = 0.08,
) -> int:
    raw_width = estimated_raw_text_width(text, cap_units=cap_units)
    dynamic_buffer = max(buffer, int(raw_width * buffer_ratio))
    return max(44, int(round(raw_width + padding + dynamic_buffer)))


def _contains_any(text: str, tokens: Iterable[str]) -> bool:
    lower = text.lower()
    return any(token in text or token in lower for token in tokens)


def _numeric_ratio(samples: list[str]) -> float:
    if not samples:
        return 0.0
    hits = 0
    for sample in samples:
        stripped = str(sample).strip()
        if re.search(r"^[+-]?\d+(?:\.\d+)?%?$", stripped) or re.search(r"^[+-]?\d+(?:\.\d+)?pp$", stripped, re.I):
            hits += 1
    return hits / max(1, len(samples))


def _marker_ratio(samples: list[str], markers: Iterable[str]) -> float:
    if not samples:
        return 0.0
    marker_tuple = tuple(markers)
    hits = 0
    for sample in samples:
        if any(marker in sample for marker in marker_tuple):
            hits += 1
    return hits / max(1, len(samples))


def _prose_ratio(samples: list[str]) -> float:
    if not samples:
        return 0.0
    hits = sum(1 for sample in samples if PROSE_HINT_RE.search(sample))
    return hits / max(1, len(samples))


def _value_hint_ratio(samples: list[str]) -> float:
    if not samples:
        return 0.0
    hits = sum(1 for sample in samples if VALUE_HINT_RE.search(sample))
    return hits / max(1, len(samples))


def classify_column(label: str, samples: Iterable[str] | None = None, column_count: int = 0) -> ColumnRole:
    sample_list = [str(sample).strip() for sample in samples or [] if str(sample).strip()]
    label_text = str(label or "").strip()
    reasons: list[str] = []
    max_units = max([longest_display_units(sample) for sample in sample_list[:40]] or [0])
    avg_units = sum(longest_display_units(sample) for sample in sample_list[:40]) / max(1, min(len(sample_list), 40))
    prose_ratio = _prose_ratio(sample_list[:40])
    value_hint_ratio = _value_hint_ratio(sample_list[:40])
    numeric_ratio = _numeric_ratio(sample_list[:40])

    if _contains_any(label_text, DIMENSION_TOKENS) and not _contains_any(label_text, ("名称", "姓名", "负责人", "owner", "name")):
        return ColumnRole("dimension", 0.9, ("dimension-token",))
    if _contains_any(label_text, LONG_TEXT_TOKENS):
        return ColumnRole("long-text", 0.92, ("long-text-label",))
    if _contains_any(label_text, STATUS_TOKENS) or _marker_ratio(sample_list[:40], STATUS_MARKERS) >= 0.5:
        return ColumnRole("status", 0.95, ("status-token",))
    if _contains_any(label_text, RANK_TOKENS):
        return ColumnRole("rank", 0.95, ("rank-token",))
    if _contains_any(label_text, DATE_TOKENS):
        return ColumnRole("date", 0.9, ("date-token",))
    if _contains_any(label_text, GENERIC_VALUE_LABELS) and max_units >= 20 and prose_ratio >= 0.18 and value_hint_ratio >= 0.35:
        return ColumnRole("mixed-value", 0.88, ("generic-value-mixed-samples",))
    if _contains_any(label_text, METRIC_TOKENS):
        if max_units >= 22 and prose_ratio >= 0.35 and value_hint_ratio >= 0.35:
            return ColumnRole("mixed-value", 0.82, ("metric-label-mixed-samples",))
        return ColumnRole("metric", 0.9, ("metric-label",))
    if _contains_any(label_text, NAME_TOKENS):
        return ColumnRole("name", 0.9, ("name-label",))

    if numeric_ratio >= 0.65:
        return ColumnRole("metric", 0.82, ("numeric-samples",))

    if max_units >= 22 and prose_ratio >= 0.35 and value_hint_ratio >= 0.35:
        return ColumnRole("mixed-value", 0.72, ("mixed-value-samples",))

    if max_units >= 36 or avg_units >= 22:
        return ColumnRole("long-text", 0.78, ("long-samples",))

    if not label_text and numeric_ratio < 0.2 and any(_contains_any(sample, NAME_TOKENS) for sample in sample_list[:12]):
        return ColumnRole("name", 0.72, ("name-samples",))

    if column_count >= 8 and len(label_text) <= 8:
        reasons.append("wide-table-compact-dimension")
    return ColumnRole("dimension", 0.62, tuple(reasons))
