"""
V语言的命令行工具

具体用法：
    python3 src/v_cli.py --encode "你好 Hello"
    python src/v_cli.py --decode "020448656C6C6F"
    python src/v_cli.py --encode "你好 Hello" --output hello.V
    python src/v_cli.py --input hello.V
    python src/v_cli.py --encode-file article.md --output article.V
    python src/v_cli.py --decode-file article.V --output article.md
    python src/v_cli.py --encode-file article.html --output article.V
    python src/v_cli.py --decode-file article.V --output article.html
"""

# 导入命令行参数解析库
import argparse
# 导入系统相关模块
import sys
# 导入路径处理模块
from pathlib import Path

# 把 src 目录加入模块搜索路径，让脚本能找到 v_codec.py
sys.path.insert(0, str(Path(__file__).parent))

# 从编解码器导入核心函数
from v_codec import chinese_to_v, v_to_chinese


def bytes_to_hex(data: bytes) -> str:
    """
    把字节转成连续十六进制字符串
    例如:b'\x02\x04' -> "0204"
    """
    # 调用 bytes 的 hex 方法得到十六进制字符串
    return data.hex()


def hex_to_bytes(hex_str: str) -> bytes:
    """
    把连续十六进制字符串转成字节
    例如："0204" -> b'\x02\x04'
    """
    # 调用 bytes.fromhex 把十六进制字符串还原成字节
    return bytes.fromhex(hex_str)


def write_v_file(path: str, data: bytes) -> None:
    """
    把 V语字节写入 .V 文件
    文件格式：[4字节长度头（大端序）][码点流]
    """
    # 以二进制写模式打开文件
    with open(path, "wb") as f:
        # 把数据长度转成 4 字节大端序整数，作为文件头写入
        f.write(len(data).to_bytes(4, "big"))
        # 写入实际的 V语码点流
        f.write(data)


def read_v_file(path: str) -> bytes:
    """
    从 .V 文件读取 V语字节
    先读 4 字节长度头，再读指定长度的码点流
    """
    # 以二进制读模式打开文件
    with open(path, "rb") as f:
        # 读取 4 字节长度头
        length_bytes = f.read(4)
        # 把长度头从大端序字节转成整数
        length = int.from_bytes(length_bytes, "big")
        # 根据长度读取后面的码点流
        data = f.read(length)
    # 返回读取到的码点流
    return data


def is_v_file(path: str) -> bool:
    """
    判断文件路径是不是 .V 文件
    不区分大小写检查后缀
    """
    # 把路径转成小写，检查后缀是不是 .v
    return path.lower().endswith(".v")


def main():
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(
        # 程序简短描述
        description="V语命令行-在文本文件与 .V 文件之间互相转换",
        # 帮助信息末尾的示例说明
        epilog="""
    示例：
        python src/v_cli.py --encode "你好 Hello"
        python src/v_cli.py --decode "020448656c6c6f"
        python src/v_cli.py --input hello.V
        python src/v_cli.py --encode-file article.md --output article.V
        python src/v_cli.py --decode-file article.V --output article.md
        python src/v_cli.py --encode-file article.html --output article.V
        python src/v_cli.py --decode-file article.V --output article.html
        """,
        # 使用原始描述格式，保留示例中的换行
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    # 添加 --encode 参数：编码字符串
    parser.add_argument(
        "--encode",
        type=str,
        metavar="TEXT",
        help="把汉语/英文字符串编码成 V语十六进制"
    )

    # 添加 --decode 参数：解码十六进制
    parser.add_argument(
        "--decode",
        type=str,
        metavar="HEX",
        help="把 V语十六进制字符串解码成汉语/英文"
    )

    # 添加 --input 参数：从 .V 文件读取并显示
    parser.add_argument(
        "--input",
        type=str,
        metavar="FILE.V",
        help="从 .V 文件读取 V语字节并解码显示"
    )

    # 添加 --encode-file / --input-file 参数：文本文件 → .V 文件
    # 两个名字指向同一个参数，保留旧用法兼容
    parser.add_argument(
        "--encode-file", "--input-file",
        type=str,
        dest="encode_file",
        metavar="FILE.TXT",
        help="读取 UTF-8 文本文件并编码成 V语，例如 .txt/.md/.html/.csv/.json/.py"
    )

    # 添加 --decode-file 参数：.V 文件 → 文本文件
    parser.add_argument(
        "--decode-file",
        type=str,
        dest="decode_file",
        metavar="FILE.V",
        help="读取 .V 文件并解码成文本文件"
    )

    # 添加 --output 参数：输出到文件
    parser.add_argument(
        "--output",
        type=str,
        metavar="FILE",
        help="指定输出文件，.V 表示二进制，其他后缀按 UTF-8 文本写入"
    )

    # 解析命令行参数
    args = parser.parse_args()

    # 如果用户指定了 --encode
    if args.encode:
        # 把输入字符串编码成 V语字节
        data = chinese_to_v(args.encode)
        # 把 V语字节转成十六进制字符串
        hex_str = bytes_to_hex(data)

        # 如果同时指定了 --output，写入 .V 文件
        if args.output:
            # 调用 write_v_file 写入带长度头的 .V 文件
            write_v_file(args.output, data)
            # 提示保存成功
            print(f"已保存到: {args.output}")
            # 显示十六进制
            print(f"十六进制: {hex_str}")
        else:
            # 没有 --output，直接在终端显示
            print(f"原文: {args.encode}")
            # 显示 V语字节
            print(f"V语字节: {data}")
            # 显示十六进制
            print(f"十六进制: {hex_str}")

    # 如果用户指定了 --decode
    elif args.decode:
        # 把十六进制字符串转成 V语字节
        data = hex_to_bytes(args.decode)
        # 把 V语字节解码成字符串
        text = v_to_chinese(data)

        # 显示输入的十六进制
        print(f"十六进制: {args.decode}")
        # 显示 V语字节
        print(f"V语字节: {data}")
        # 显示解码结果
        print(f"解码: {text}")

    # 如果用户指定了 --input
    elif args.input:
        # 从 .V 文件读取 V语字节（带 4 字节长度头）
        data = read_v_file(args.input)
        # 把 V语字节解码成字符串
        text = v_to_chinese(data)
        # 把 V语字节转成十六进制字符串
        hex_str = bytes_to_hex(data)

        # 显示文件名
        print(f"文件名： {args.input}")
        # 显示 V语字节
        print(f"V语字节: {data}")
        # 显示十六进制
        print(f"十六进制: {hex_str}")
        # 显示解码结果
        print(f"解码: {text}")

    # 如果用户指定了 --encode-file / --input-file
    elif args.encode_file:
        # 以 UTF-8 读取文本文件
        with open(args.encode_file, "r", encoding="utf-8") as f:
            # 完整读取文件内容，保留首尾换行和缩进
            text = f.read()

        # 把文本编码成 V语字节
        data = chinese_to_v(text)
        # 把 V语字节转成十六进制字符串
        hex_str = bytes_to_hex(data)

        # 如果同时指定了 --output
        if args.output:
            # 判断输出文件是不是 .V 文件
            if is_v_file(args.output):
                # 调用 write_v_file 写入带长度头的 .V 文件
                write_v_file(args.output, data)
            else:
                # 否则直接写 UTF-8 文本文件
                with open(args.output, "w", encoding="utf-8") as f:
                    # 把原文写出去
                    f.write(text)
            # 提示读取成功
            print(f"已读取: {args.encode_file}")
            # 提示保存成功
            print(f"已保存到: {args.output}")
            # 显示十六进制
            print(f"十六进制: {hex_str}")

        else:
            # 没有 --output，直接在终端显示
            print(f"文件: {args.encode_file}")
            # 显示原文前 100 字，超过则加省略号
            print(f"原文: {text[:100]}{'...' if len(text) > 100 else ''}")
            # 显示 V语字节
            print(f"V语字节: {data}")
            # 显示十六进制
            print(f"十六进制: {hex_str}")

    # 如果用户指定了 --decode-file
    elif args.decode_file:
        # 从 .V 文件读取 V语字节（带 4 字节长度头）
        data = read_v_file(args.decode_file)
        # 把 V语字节解码成字符串
        text = v_to_chinese(data)
        # 把 V语字节转成十六进制字符串
        hex_str = bytes_to_hex(data)

        # 如果同时指定了 --output
        if args.output:
            # 判断输出文件是不是 .V 文件
            if is_v_file(args.output):
                # 再写回 .V 文件
                write_v_file(args.output, data)
            else:
                # 否则写成 UTF-8 文本文件
                with open(args.output, "w", encoding="utf-8") as f:
                    # 把解码后的文本写出去
                    f.write(text)
            # 提示读取成功
            print(f"已读取: {args.decode_file}")
            # 提示保存成功
            print(f"已保存到: {args.output}")
            # 显示十六进制
            print(f"十六进制: {hex_str}")

        else:
            # 没有 --output，直接在终端显示
            print(f"文件: {args.decode_file}")
            # 显示 V语字节
            print(f"V语字节: {data}")
            # 显示十六进制
            print(f"十六进制: {hex_str}")
            # 显示解码结果前 100 字，超过则加省略号
            print(f"解码: {text[:100]}{'...' if len(text) > 100 else ''}")

    # 如果没有指定任何参数
    else:
        # 打印帮助信息
        parser.print_help()


# 如果直接运行这个脚本
if __name__ == "__main__":
    # 调用主函数
    main()
