from __future__ import annotations

from dataclasses import dataclass
import unicodedata

# 用空元组表示 epsilon 产生式，这样入栈时更方便处理。
EPSILON = "ε"
END_MARKER = "#"


@dataclass(frozen=True)
class Production:
    """一条产生式，例如 S -> MH。"""

    left: str
    right: tuple[str, ...]

    def display(self) -> str:
        """把产生式转成适合输出的字符串。"""
        return f"{self.left} -> {''.join(self.right) if self.right else EPSILON}"


@dataclass
class AnalysisStep:
    """记录 LL(1) 分析过程中的一步。"""

    step_no: int
    stack: str
    remaining_input: str
    action: str


@dataclass
class ParseResult:
    """保存一次输入串分析的最终结果。"""

    original_sentence: str
    normalized_sentence: str
    accepted: bool
    message: str
    steps: list[AnalysisStep]


class LL1Grammar:
    """一个尽量小而清晰的 LL(1) 文法工具类。"""

    def __init__(
        self,
        productions: dict[str, list[tuple[str, ...]]],
        start_symbol: str,
        terminal_order: list[str] | None = None,
    ) -> None:
        self.productions = productions
        self.start_symbol = start_symbol
        self.nonterminals = list(productions.keys())

        auto_terminals: list[str] = []
        for alternatives in productions.values():
            for right in alternatives:
                for symbol in right:
                    if symbol in productions or symbol == EPSILON:
                        continue
                    if symbol not in auto_terminals:
                        auto_terminals.append(symbol)

        self.terminals = terminal_order or auto_terminals

    def is_nonterminal(self, symbol: str) -> bool:
        """判断一个符号是否是非终结符。"""
        return symbol in self.productions

    def first_of_sequence(
        self,
        symbols: tuple[str, ...],
        first_sets: dict[str, set[str]],
    ) -> set[str]:
        """
        计算一个符号串的 FIRST 集。

        例如：
        - FIRST(MH)
        - FIRST(LSo)
        - FIRST(ε)
        """
        if not symbols:
            return {EPSILON}

        result: set[str] = set()

        for symbol in symbols:
            if not self.is_nonterminal(symbol):
                result.add(symbol)
                return result

            result.update(first_sets[symbol] - {EPSILON})

            if EPSILON not in first_sets[symbol]:
                return result

        result.add(EPSILON)
        return result

    def compute_first_sets(self) -> dict[str, set[str]]:
        """使用不动点迭代法计算所有非终结符的 FIRST 集。"""
        first_sets = {nonterminal: set() for nonterminal in self.nonterminals}

        changed = True
        while changed:
            changed = False

            for left, alternatives in self.productions.items():
                for right in alternatives:
                    before_size = len(first_sets[left])
                    first_sets[left].update(self.first_of_sequence(right, first_sets))
                    if len(first_sets[left]) != before_size:
                        changed = True

        return first_sets

    def compute_follow_sets(
        self,
        first_sets: dict[str, set[str]],
    ) -> dict[str, set[str]]:
        """使用不动点迭代法计算所有非终结符的 FOLLOW 集。"""
        follow_sets = {nonterminal: set() for nonterminal in self.nonterminals}
        follow_sets[self.start_symbol].add(END_MARKER)

        changed = True
        while changed:
            changed = False

            for left, alternatives in self.productions.items():
                for right in alternatives:
                    for index, symbol in enumerate(right):
                        if not self.is_nonterminal(symbol):
                            continue

                        beta = right[index + 1 :]
                        first_beta = self.first_of_sequence(beta, first_sets)

                        before_size = len(follow_sets[symbol])
                        follow_sets[symbol].update(first_beta - {EPSILON})

                        if EPSILON in first_beta:
                            follow_sets[symbol].update(follow_sets[left])

                        if len(follow_sets[symbol]) != before_size:
                            changed = True

        return follow_sets

    def build_parsing_table(
        self,
        first_sets: dict[str, set[str]],
        follow_sets: dict[str, set[str]],
    ) -> tuple[dict[str, dict[str, Production | None]], list[str]]:
        """
        构造预测分析表。

        返回值包含两部分：
        1. 预测分析表本身
        2. 冲突说明列表，若为空则说明该文法可视为 LL(1)
        """
        table = {
            nonterminal: {terminal: None for terminal in self.terminals + [END_MARKER]}
            for nonterminal in self.nonterminals
        }
        conflicts: list[str] = []

        for left, alternatives in self.productions.items():
            for right in alternatives:
                production = Production(left, right)
                first_alpha = self.first_of_sequence(right, first_sets)

                for terminal in first_alpha - {EPSILON}:
                    self._put_table_entry(table, terminal, production, conflicts)

                if EPSILON in first_alpha:
                    for terminal in follow_sets[left]:
                        self._put_table_entry(table, terminal, production, conflicts)

        return table, conflicts

    def _put_table_entry(
        self,
        table: dict[str, dict[str, Production | None]],
        terminal: str,
        production: Production,
        conflicts: list[str],
    ) -> None:
        """向预测分析表中放入一条表项，并检查是否冲突。"""
        current = table[production.left][terminal]

        if current is None:
            table[production.left][terminal] = production
            return

        if current != production:
            conflicts.append(
                f"表项 M[{production.left}, {terminal}] 同时出现 "
                f"{current.display()} 和 {production.display()}"
            )

    def analyze_sentence(
        self,
        sentence: str,
        table: dict[str, dict[str, Production | None]],
    ) -> ParseResult:
        """根据预测分析表，模拟一个输入串的 LL(1) 分析过程。"""
        normalized_sentence = normalize_sentence(sentence)
        symbols = list(normalized_sentence)
        allowed_symbols = set(self.terminals + [END_MARKER])

        for symbol in symbols:
            if symbol not in allowed_symbols:
                return ParseResult(
                    original_sentence=sentence,
                    normalized_sentence=normalized_sentence,
                    accepted=False,
                    message=f"输入串中出现了文法未定义的符号：{symbol}",
                    steps=[],
                )

        stack = [END_MARKER, self.start_symbol]
        pointer = 0
        steps: list[AnalysisStep] = []
        step_no = 1

        while True:
            stack_snapshot = "".join(stack)
            remaining_input = "".join(symbols[pointer:])
            top = stack[-1]
            current = symbols[pointer]

            if top == current == END_MARKER:
                steps.append(
                    AnalysisStep(step_no, stack_snapshot, remaining_input, "分析成功，输入串被接受")
                )
                return ParseResult(
                    original_sentence=sentence,
                    normalized_sentence=normalized_sentence,
                    accepted=True,
                    message="输入串符合该文法。",
                    steps=steps,
                )

            if not self.is_nonterminal(top):
                if top == current:
                    steps.append(
                        AnalysisStep(
                            step_no,
                            stack_snapshot,
                            remaining_input,
                            f"匹配终结符 {current}",
                        )
                    )
                    stack.pop()
                    pointer += 1
                    step_no += 1
                    continue

                steps.append(
                    AnalysisStep(
                        step_no,
                        stack_snapshot,
                        remaining_input,
                        f"栈顶符号 {top} 与当前输入 {current} 不匹配，分析失败",
                    )
                )
                return ParseResult(
                    original_sentence=sentence,
                    normalized_sentence=normalized_sentence,
                    accepted=False,
                    message="栈顶终结符与当前输入不匹配。",
                    steps=steps,
                )

            production = table[top].get(current)
            if production is None:
                steps.append(
                    AnalysisStep(
                        step_no,
                        stack_snapshot,
                        remaining_input,
                        f"预测分析表中不存在 M[{top}, {current}]，分析失败",
                    )
                )
                return ParseResult(
                    original_sentence=sentence,
                    normalized_sentence=normalized_sentence,
                    accepted=False,
                    message="预测分析表中没有对应表项。",
                    steps=steps,
                )

            steps.append(
                AnalysisStep(
                    step_no,
                    stack_snapshot,
                    remaining_input,
                    f"使用产生式 {production.display()}",
                )
            )

            stack.pop()
            for symbol in reversed(production.right):
                stack.append(symbol)

            step_no += 1


def build_default_grammar() -> LL1Grammar:
    """构造实验题目中给定的文法。"""
    productions = {
        "S": [("M", "H"), ("a",)],
        "H": [("L", "S", "o"), ()],
        "K": [("d", "M", "L"), ()],
        "L": [("e", "H", "f")],
        "M": [("K",), ("b", "L", "M")],
    }

    # 这里使用题目示例中更常见的列顺序，方便和实验报告对照。
    terminal_order = ["a", "b", "d", "e", "o", "f"]
    return LL1Grammar(productions=productions, start_symbol="S", terminal_order=terminal_order)


DEFAULT_CASES = [
    ("空串", ""),
    ("最简单的句子", "a"),
    ("由 M -> bLM 推导出的句子", "bef"),
    ("由 K -> dML 推导出的句子", "def"),
    ("包含 H -> LSo 的句子", "efao"),
    ("错误示例 1", "ao"),
    ("错误示例 2", "df"),
]


def normalize_sentence(sentence: str) -> str:
    """去掉输入中的空白字符，并在末尾补上结束符 #。"""
    cleaned = "".join(sentence.split())
    if not cleaned.endswith(END_MARKER):
        cleaned += END_MARKER
    return cleaned


def sort_symbols(symbols: set[str], grammar: LL1Grammar) -> list[str]:
    """按更适合展示的顺序排列集合中的符号。"""
    display_order = grammar.terminals + [END_MARKER, EPSILON]
    return [symbol for symbol in display_order if symbol in symbols]


def format_symbol_set(symbols: set[str], grammar: LL1Grammar) -> str:
    """把 FIRST/FOLLOW 集合格式化成字符串。"""
    ordered = sort_symbols(symbols, grammar)
    return "{ " + ", ".join(ordered) + " }"


def build_text_table(headers: list[str], rows: list[list[str]]) -> str:
    """构造一个纯文本表格，便于在终端中直接查看。"""
    all_rows = [headers] + rows

    def display_width(text: str) -> int:
        """
        计算字符串在终端中的显示宽度。

        中文字符通常会占两个字符宽度，如果只用 len()，
        表格在终端里会很容易错位。
        """
        width = 0
        for char in text:
            width += 2 if unicodedata.east_asian_width(char) in {"F", "W"} else 1
        return width

    widths = [
        max(display_width(str(row[index])) for row in all_rows)
        for index in range(len(headers))
    ]

    def make_line(row: list[str]) -> str:
        cells: list[str] = []
        for index, cell in enumerate(row):
            text = str(cell)
            padding = widths[index] - display_width(text)
            cells.append(text + " " * padding)
        return " | ".join(cells)

    separator = "-+-".join("-" * width for width in widths)
    lines = [make_line(headers), separator]
    lines.extend(make_line(row) for row in rows)
    return "\n".join(lines)


def build_grammar_section(grammar: LL1Grammar) -> str:
    """输出文法本身。"""
    lines = ["文法："]
    for left, alternatives in grammar.productions.items():
        right_text = " | ".join("".join(right) if right else EPSILON for right in alternatives)
        lines.append(f"{left} -> {right_text}")
    return "\n".join(lines)


def build_first_follow_section(
    grammar: LL1Grammar,
    first_sets: dict[str, set[str]],
    follow_sets: dict[str, set[str]],
) -> str:
    """输出 FIRST 集和 FOLLOW 集。"""
    first_rows = [
        [nonterminal, format_symbol_set(first_sets[nonterminal], grammar)]
        for nonterminal in grammar.nonterminals
    ]
    follow_rows = [
        [nonterminal, format_symbol_set(follow_sets[nonterminal], grammar)]
        for nonterminal in grammar.nonterminals
    ]

    return "\n".join(
        [
            "FIRST 集：",
            build_text_table(["非终结符", "FIRST"], first_rows),
            "",
            "FOLLOW 集：",
            build_text_table(["非终结符", "FOLLOW"], follow_rows),
        ]
    )


def build_ll1_section(conflicts: list[str]) -> str:
    """输出 LL(1) 判定结果。"""
    if not conflicts:
        return "LL(1) 判定：是\n原因：预测分析表中没有冲突，因此该文法是 LL(1) 文法。"

    lines = ["LL(1) 判定：否", "原因：预测分析表存在冲突。"]
    for conflict in conflicts:
        lines.append(f"- {conflict}")
    return "\n".join(lines)


def build_parsing_table_section(
    grammar: LL1Grammar,
    table: dict[str, dict[str, Production | None]],
) -> str:
    """输出预测分析表。"""
    headers = ["非终结符"] + grammar.terminals + [END_MARKER]
    rows: list[list[str]] = []

    for nonterminal in grammar.nonterminals:
        row = [nonterminal]
        for terminal in grammar.terminals + [END_MARKER]:
            production = table[nonterminal][terminal]
            row.append(production.display() if production is not None else "")
        rows.append(row)

    return "\n".join(["预测分析表：", build_text_table(headers, rows)])


def build_analysis_section(result: ParseResult) -> str:
    """输出一个输入串的分析过程。"""
    lines = [
        f"输入串：{result.original_sentence!r}",
        f"规范化后：{result.normalized_sentence}",
        f"最终结果：{'接受' if result.accepted else '拒绝'}",
        f"说明：{result.message}",
    ]

    if not result.steps:
        return "\n".join(lines)

    rows = [
        [str(step.step_no), step.stack, step.remaining_input, step.action]
        for step in result.steps
    ]
    lines.extend(
        [
            "",
            build_text_table(["步骤", "分析栈", "剩余输入", "动作"], rows),
        ]
    )
    return "\n".join(lines)


def build_full_report(
    grammar: LL1Grammar,
    custom_sentence: str | None = None,
    example_cases: list[tuple[str, str]] | None = None,
) -> str:
    """组合出完整输出，方便 main.py 直接打印。"""
    first_sets = grammar.compute_first_sets()
    follow_sets = grammar.compute_follow_sets(first_sets)
    table, conflicts = grammar.build_parsing_table(first_sets, follow_sets)

    sections = [
        build_grammar_section(grammar),
        build_first_follow_section(grammar, first_sets, follow_sets),
        build_ll1_section(conflicts),
        build_parsing_table_section(grammar, table),
        (
            "说明：按标准 FOLLOW 集算法计算，FOLLOW(L) 中包含 #。\n"
            "这是因为 L 出现在 K -> dML 的末尾，而 K 又能出现在句型末尾。"
        ),
    ]

    if custom_sentence is not None:
        result = grammar.analyze_sentence(custom_sentence, table)
        sections.extend(["输入串分析：", build_analysis_section(result)])
        return "\n\n".join(sections)

    if example_cases:
        sections.append("内置测试示例：")
        for title, sentence in example_cases:
            result = grammar.analyze_sentence(sentence, table)
            sections.append(f"[{title}]\n{build_analysis_section(result)}")

    return "\n\n".join(sections)
