from __future__ import annotations

import argparse
import sys
from pathlib import Path

from src.lexer import Lexer, build_report


def parse_args() -> argparse.Namespace:
    """解析命令行参数。"""
    parser = argparse.ArgumentParser(
        description="实验一：词法分析程序（支持关键词、标识符、常量、运算符、界符和注释）"
    )
    parser.add_argument("source", help="待分析的源程序文件路径")
    return parser.parse_args()


def main() -> int:
    """程序入口。"""
    args = parse_args()
    source_path = Path(args.source)

    if not source_path.exists():
        print(f"错误：找不到源文件 {source_path}")
        return 1

    text = source_path.read_text(encoding="utf-8")
    lexer = Lexer(text)
    tokens, errors, symbol_table = lexer.analyze()

    print(build_report(source_path, tokens, errors, symbol_table))
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())

