"""Data models for table parsing and processing."""

from __future__ import annotations
from typing import List, Optional
from dataclasses import dataclass, field


@dataclass
class TableItem:
    """表格项数据结构，包含标题、层级、索引和表格信息。"""
    level: int = 0
    table_index: Optional[int] = None # 表格索引，形如: 1/2/3/...
    label: Optional[str] = None # 形如: table x.y.z
    section: Optional[str] = None # 形如: x.y.z
    title: Optional[str] = None # 表格标题 Table x.y.z xxx
    title_indices: List[int] = field(default_factory=list)
    footnote: Optional[str] = None
    footnote_indices: List[int] = field(default_factory=list)
    local_path: Optional[str] = None
    
    def set_table(self, table_index: int):
        """设置当前 section 的表格索引。"""
        self.table_index = table_index
    
    def add_footnote_index(self, para_index: int):
        """为当前 section 的表格追加脚注段落索引。"""
        self.footnote_indices.append(para_index)
    
    def append_footnote_text(self, text: str):
        """追加脚注文本（按段落累积，以换行分隔）。"""
        text = (text or "").strip()
        if not text:
            return
        if self.footnote:
            # 以换行分隔追加，保持原段落边界
            self.footnote += ("\n" if not self.footnote.endswith("\n") else "") + text
        else:
            self.footnote = text
    
    def get_section_label(self) -> str:
        """获取用于文件命名的标签，若无标签则返回默认值。"""
        return (self.label or 'Table')