import sqlite3
import os
import argparse
from datetime import datetime

def check_db(table_name=None, limit=20):
    db_path = r'e:\2025Code\orc-order-v3\orc-order-v3\release\data\product_cache.db'
    if not os.path.exists(db_path):
        # 尝试开发环境路径
        db_path = r'e:\2025Code\orc-order-v3\orc-order-v3\data\product_cache.db'
        
    if not os.path.exists(db_path):
        print(f"错误: 找不到数据库文件 {db_path}")
        return

    print(f"正在读取数据库: {db_path}")
    print("-" * 60)

    try:
        conn = sqlite3.connect(db_path)
        conn.row_factory = sqlite3.Row
        cursor = conn.cursor()

        # 获取所有表名
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
        tables = [row[0] for row in cursor.fetchall() if row[0] != 'sqlite_sequence']

        if not table_name:
            print(f"数据库中的表: {', '.join(tables)}")
            print("\n使用 'python check_db.py [表名]' 查看具体内容")
            
            # 默认显示一些汇总信息
            for table in tables:
                cursor.execute(f"SELECT COUNT(*) FROM {table}")
                count = cursor.fetchone()[0]
                print(f"  - {table}: {count} 条记录")
        
        target_tables = [table_name] if table_name else tables

        for table in target_tables:
            if table not in tables:
                print(f"\n警告: 表 '{table}' 不存在")
                continue

            print(f"\n=== 表: {table} (最近 {limit} 条) ===")
            cursor.execute(f"SELECT * FROM {table} LIMIT {limit}")
            rows = cursor.fetchall()
            
            if not rows:
                print("  (空)")
                continue

            # 打印表头
            keys = rows[0].keys()
            header = " | ".join(f"{str(k):<15}" for k in keys)
            print(header)
            print("-" * len(header))

            # 打印行
            for row in rows:
                print(" | ".join(f"{str(row[k])[:15]:<15}" for k in keys))

        conn.close()
    except Exception as e:
        print(f"读取数据库出错: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="查看 OCR 系统数据库内容")
    parser.add_argument("table", nargs="?", help="要查看的表名 (products, order_metadata, missing_barcodes)")
    parser.add_argument("--limit", type=int, default=20, help="显示记录条数 (默认 20)")
    
    args = parser.parse_args()
    check_db(args.table, args.limit)
