from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
import unicodedata

# 关键字的内码。
KEYWORD_CODES = {
    "int": 1,
    "float": 2,
    "char": 3,
    "void": 4,
    "if": 5,
    "else": 6,
    "while": 7,
    "for": 8,
    "return": 9,
    "break": 10,
    "continue": 11,
}

# 运算符的内码。
OPERATOR_CODES = {
    "==": 101,
    "!=": 102,
    "<=": 103,
    ">=": 104,
    "&&": 105,
    "||": 106,
    "++": 107,
    "--": 108,
    "+=": 109,
    "-=": 110,
    "*=": 111,
    "/=": 112,
    "%=": 113,
    "=": 114,
    "+": 115,
    "-": 116,
    "*": 117,
    "/": 118,
    "%": 119,
    "<": 120,
    ">": 121,
    "!": 122,
}

# 界符的内码。
DELIMITER_CODES = {
    "(": 201,
    ")": 202,
    "{": 203,
    "}": 204,
    "[": 205,
    "]": 206,
    ",": 207,
    ";": 208,
    ".": 209,
}

# 其他单词种别的内码。
SPECIAL_CODES = {
    "IDENTIFIER": 300,
    "INTEGER": 301,
    "REAL": 302,
    "CHAR": 303,
    "STRING": 304,
}

# 为了优先识别双字符运算符，需要按长度从长到短匹配。
SORTED_OPERATORS = sorted(OPERATOR_CODES, key=len, reverse=True)


@dataclass
class Token:
    """一个 token 就是词法分析得到的最小语法单元。"""

    kind: str
    lexeme: str
    code: int
    attribute: object
    line: int
    column: int


@dataclass
class LexicalError:
    """记录词法错误，方便最后统一输出。"""

    message: str
    line: int
    column: int


class Lexer:
    """一个尽量小而清晰的词法分析器。"""

    def __init__(self, text: str) -> None:
        self.text = text
        self.index = 0
        self.line = 1
        self.column = 1

        self.tokens: list[Token] = []
        self.errors: list[LexicalError] = []

        # 标识符表使用“列表 + 映射”保存。
        # 列表用于按顺序输出，映射用于快速查重。
        self.symbol_table: list[str] = []
        self.symbol_index: dict[str, int] = {}

    def analyze(self) -> tuple[list[Token], list[LexicalError], list[str]]:
        """循环扫描整个源程序，直到读到文件末尾。"""
        while (current := self.current_char()) is not None:
            if current.isspace():
                self.skip_whitespace()
                continue

            if current == "/" and self.peek() == "/":
                self.skip_single_line_comment()
                continue

            if current == "/" and self.peek() == "*":
                self.skip_multi_line_comment()
                continue

            if current.isalpha() or current == "_":
                self.scan_identifier_or_keyword()
                continue

            if current.isdigit():
                self.scan_number()
                continue

            if current == "'":
                self.scan_char_literal()
                continue

            if current == '"':
                self.scan_string_literal()
                continue

            if self.scan_operator_or_delimiter():
                continue

            # 走到这里，说明当前字符无法被识别，属于词法错误。
            self.add_error(f"无法识别的字符：{current!r}", self.line, self.column)
            self.advance()

        return self.tokens, self.errors, self.symbol_table

    def current_char(self) -> str | None:
        """返回当前字符；如果越界则返回 None。"""
        if self.index >= len(self.text):
            return None
        return self.text[self.index]

    def peek(self, offset: int = 1) -> str | None:
        """向前偷看若干个字符，但不真正移动位置。"""
        target = self.index + offset
        if target >= len(self.text):
            return None
        return self.text[target]

    def advance(self) -> str | None:
        """读取当前字符，并把扫描位置移动到下一个字符。"""
        current = self.current_char()
        if current is None:
            return None

        self.index += 1
        if current == "\n":
            self.line += 1
            self.column = 1
        else:
            self.column += 1
        return current

    def add_error(self, message: str, line: int, column: int) -> None:
        """添加一条词法错误。"""
        self.errors.append(LexicalError(message, line, column))

    def add_token(
        self,
        kind: str,
        lexeme: str,
        code: int,
        attribute: object,
        line: int,
        column: int,
    ) -> None:
        """添加一条 token。"""
        self.tokens.append(Token(kind, lexeme, code, attribute, line, column))

    def skip_whitespace(self) -> None:
        """跳过空格、换行、制表符等空白字符。"""
        while (current := self.current_char()) is not None and current.isspace():
            self.advance()

    def skip_single_line_comment(self) -> None:
        """跳过 // 注释。"""
        self.advance()
        self.advance()
        while (current := self.current_char()) is not None and current != "\n":
            self.advance()

    def skip_multi_line_comment(self) -> None:
        """跳过 /* ... */ 注释；如果注释没有结束则报错。"""
        start_line, start_column = self.line, self.column
        self.advance()
        self.advance()

        while (current := self.current_char()) is not None:
            if current == "*" and self.peek() == "/":
                self.advance()
                self.advance()
                return
            self.advance()

        self.add_error("多行注释没有正常结束", start_line, start_column)

    def scan_identifier_or_keyword(self) -> None:
        """识别关键字或标识符。"""
        start_line, start_column = self.line, self.column
        chars: list[str] = []

        while (current := self.current_char()) is not None and (
            current.isalnum() or current == "_"
        ):
            chars.append(self.advance() or "")

        lexeme = "".join(chars)

        if lexeme in KEYWORD_CODES:
            self.add_token(
                kind="关键字",
                lexeme=lexeme,
                code=KEYWORD_CODES[lexeme],
                attribute="-",
                line=start_line,
                column=start_column,
            )
            return

        attribute = self.intern_identifier(lexeme)
        self.add_token(
            kind="标识符",
            lexeme=lexeme,
            code=SPECIAL_CODES["IDENTIFIER"],
            attribute=attribute,
            line=start_line,
            column=start_column,
        )

    def scan_number(self) -> None:
        """识别整数或实数。"""
        start_line, start_column = self.line, self.column
        chars: list[str] = []
        is_real = False

        while (current := self.current_char()) is not None and current.isdigit():
            chars.append(self.advance() or "")

        # 形如 12.34 的单词识别为实数。
        if self.current_char() == "." and (next_char := self.peek()) is not None and next_char.isdigit():
            is_real = True
            chars.append(self.advance() or "")
            while (current := self.current_char()) is not None and current.isdigit():
                chars.append(self.advance() or "")

        # 形如 123abc 属于非法数字。
        if (current := self.current_char()) is not None and (
            current.isalpha() or current == "_"
        ):
            while (current := self.current_char()) is not None and (
                current.isalnum() or current == "_"
            ):
                chars.append(self.advance() or "")
            bad_lexeme = "".join(chars)
            self.add_error(f"非法数字常量：{bad_lexeme}", start_line, start_column)
            return

        lexeme = "".join(chars)
        if is_real:
            self.add_token(
                kind="实数",
                lexeme=lexeme,
                code=SPECIAL_CODES["REAL"],
                attribute=float(lexeme),
                line=start_line,
                column=start_column,
            )
        else:
            self.add_token(
                kind="整数",
                lexeme=lexeme,
                code=SPECIAL_CODES["INTEGER"],
                attribute=int(lexeme),
                line=start_line,
                column=start_column,
            )

    def scan_char_literal(self) -> None:
        """识别字符常量，例如 'a' 或 '\\n'。"""
        start_line, start_column = self.line, self.column
        self.advance()
        chars: list[str] = []

        while (current := self.current_char()) is not None:
            if current == "\n":
                self.add_error("字符常量不能跨行", start_line, start_column)
                return

            if current == "\\":
                chars.append(self.advance() or "")
                if self.current_char() is None:
                    break
                chars.append(self.advance() or "")
                continue

            if current == "'":
                self.advance()
                lexeme = "'" + "".join(chars) + "'"
                content = "".join(chars)
                if not content:
                    self.add_error("空字符常量不合法", start_line, start_column)
                    return
                self.add_token(
                    kind="字符常量",
                    lexeme=lexeme,
                    code=SPECIAL_CODES["CHAR"],
                    attribute=content,
                    line=start_line,
                    column=start_column,
                )
                return

            chars.append(self.advance() or "")

        self.add_error("字符常量没有正常结束", start_line, start_column)

    def scan_string_literal(self) -> None:
        """识别字符串常量，例如 \"hello\"。"""
        start_line, start_column = self.line, self.column
        self.advance()
        chars: list[str] = []

        while (current := self.current_char()) is not None:
            if current == "\n":
                self.add_error("字符串常量不能跨行", start_line, start_column)
                return

            if current == "\\":
                chars.append(self.advance() or "")
                if self.current_char() is None:
                    break
                chars.append(self.advance() or "")
                continue

            if current == '"':
                self.advance()
                lexeme = '"' + "".join(chars) + '"'
                self.add_token(
                    kind="字符串常量",
                    lexeme=lexeme,
                    code=SPECIAL_CODES["STRING"],
                    attribute="".join(chars),
                    line=start_line,
                    column=start_column,
                )
                return

            chars.append(self.advance() or "")

        self.add_error("字符串常量没有正常结束", start_line, start_column)

    def scan_operator_or_delimiter(self) -> bool:
        """识别运算符或界符。成功返回 True，失败返回 False。"""
        start_line, start_column = self.line, self.column

        for operator in SORTED_OPERATORS:
            if self.text.startswith(operator, self.index):
                for _ in operator:
                    self.advance()
                self.add_token(
                    kind="运算符",
                    lexeme=operator,
                    code=OPERATOR_CODES[operator],
                    attribute="-",
                    line=start_line,
                    column=start_column,
                )
                return True

        current = self.current_char()
        if current in DELIMITER_CODES:
            self.advance()
            self.add_token(
                kind="界符",
                lexeme=current,
                code=DELIMITER_CODES[current],
                attribute="-",
                line=start_line,
                column=start_column,
            )
            return True

        return False

    def intern_identifier(self, name: str) -> int:
        """把标识符放进标识符表，并返回它的编号。"""
        if name not in self.symbol_index:
            self.symbol_table.append(name)
            self.symbol_index[name] = len(self.symbol_table)
        return self.symbol_index[name]


def build_report(
    source_path: Path,
    tokens: list[Token],
    errors: list[LexicalError],
    symbol_table: list[str],
) -> str:
    """把分析结果整理成适合直接展示或粘贴到报告里的文本。"""
    lines: list[str] = []
    lines.append("实验一：词法分析结果")
    lines.append(f"源文件：{source_path}")
    lines.append("")
    lines.append(
        f"共识别出 {len(tokens)} 个 token，{len(symbol_table)} 个标识符，{len(errors)} 个词法错误。"
    )
    lines.append("")
    lines.append("一、Token 二元式")

    if not tokens:
        lines.append("（没有识别到 token）")
    else:
        token_rows = [
            [
                str(index),
                f"{token.line}:{token.column}",
                token.lexeme,
                token.kind,
                f"({token.code}, {token.attribute})",
            ]
            for index, token in enumerate(tokens, start=1)
        ]
        lines.extend(
            render_table(
                headers=["序号", "位置", "单词", "种别", "二元式(code, attr)"],
                rows=token_rows,
                aligns=["right", "right", "left", "left", "left"],
            )
        )

    lines.append("")
    lines.append("二、标识符表")
    if not symbol_table:
        lines.append("（没有标识符）")
    else:
        symbol_rows = [[str(index), name] for index, name in enumerate(symbol_table, start=1)]
        lines.extend(
            render_table(
                headers=["编号", "标识符"],
                rows=symbol_rows,
                aligns=["right", "left"],
            )
        )

    lines.append("")
    lines.append("三、词法错误")
    if not errors:
        lines.append("未发现词法错误。")
    else:
        error_rows = [
            [str(index), str(error.line), str(error.column), error.message]
            for index, error in enumerate(errors, start=1)
        ]
        lines.extend(
            render_table(
                headers=["序号", "行", "列", "错误信息"],
                rows=error_rows,
                aligns=["right", "right", "right", "left"],
            )
        )

    return "\n".join(lines)


def render_table(
    headers: list[str],
    rows: list[list[str]],
    aligns: list[str] | None = None,
) -> list[str]:
    """把二维数据渲染成更整齐的纯文本表格。"""
    if aligns is None:
        aligns = ["left"] * len(headers)

    widths = [display_width(header) for header in headers]
    for row in rows:
        for index, cell in enumerate(row):
            widths[index] = max(widths[index], display_width(cell))

    border = "+" + "+".join("-" * (width + 2) for width in widths) + "+"
    header_line = "| " + " | ".join(
        pad_text(header, widths[index], aligns[index]) for index, header in enumerate(headers)
    ) + " |"

    lines = [border, header_line, border]
    for row in rows:
        row_line = "| " + " | ".join(
            pad_text(cell, widths[index], aligns[index]) for index, cell in enumerate(row)
        ) + " |"
        lines.append(row_line)
    lines.append(border)
    return lines


def pad_text(text: str, width: int, align: str = "left") -> str:
    """按显示宽度补空格，避免中文列名或内容错位。"""
    padding = max(width - display_width(text), 0)
    if align == "right":
        return " " * padding + text
    return text + " " * padding


def display_width(text: str) -> int:
    """计算字符串在终端中的显示宽度。"""
    width = 0
    for char in text:
        if unicodedata.combining(char):
            continue
        if unicodedata.east_asian_width(char) in {"W", "F"}:
            width += 2
        else:
            width += 1
    return width
