#!/usr/bin/env python3
"""
WPS口径字数统计工具
朝暮 ICE-GL-CM001 · 明天见频道 · novel-system

WPS统计规则：
- 中文字符 = 1字
- 中文标点 = 1字
- 英文单词 = 1字（连续的字母序列）
- 数字序列 = 1字（连续的数字）
- 英文空格 = 不计
- 纯英文标点 = 不计

用法: python3 wps_wordcount.py <文件路径>
      python3 wps_wordcount.py <文件夹路径>  # 批量统计
"""

import sys, os, re

def wps_word_count(text):
    """WPS口径字数统计"""
    chinese = len(re.findall(r'[\u4e00-\u9fff\u3000-\u303f\uff00-\uffef\u2018-\u201f\u2026\u2027]', text))
    en_words = len(re.findall(r'[a-zA-Z0-9]+', text))
    return chinese + en_words

def count_file(filepath):
    """统计单个文件"""
    with open(filepath, 'r', encoding='utf-8') as f:
        text = f.read()
    return wps_word_count(text)

def count_directory(dirpath):
    """统计目录下所有txt文件"""
    results = []
    for fname in sorted(os.listdir(dirpath)):
        if fname.endswith('.txt'):
            fpath = os.path.join(dirpath, fname)
            wc = count_file(fpath)
            results.append((fname, wc))
    return results

def main():
    if len(sys.argv) < 2:
        print("用法: python3 wps_wordcount.py <文件或目录路径>")
        sys.exit(1)

    path = sys.argv[1]

    if os.path.isfile(path):
        wc = count_file(path)
        print(f"{os.path.basename(path)}: {wc} 字（WPS口径）")
    elif os.path.isdir(path):
        results = count_directory(path)
        total = 0
        print(f"{'文件名':<40} {'字数':>8} {'状态':>6}")
        print("-" * 56)
        for fname, wc in results:
            status = '✅' if 2000 <= wc <= 2200 else ('🔶' if wc < 2000 else '🔴')
            print(f"{fname:<40} {wc:>8} {status:>6}")
            total += wc
        print("-" * 56)
        print(f"{'合计':<40} {total:>8}")
    else:
        print(f"错误: '{path}' 不存在")
        sys.exit(1)

if __name__ == '__main__':
    main()
