#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查结账数据 JSON 文件的结构，了解实际字段名称

用法：
    cd C:/NeoZQYY
    python scripts/ops/_inspect_settlement_json.py
"""

import json
import os
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

# 加载环境变量
from dotenv import load_dotenv
load_dotenv(project_root / ".env")

def main():
    """检查结账数据的实际结构"""
    
    # 查找最新的结账数据文件
    log_dir = Path(os.environ["SYSTEM_LOG_ROOT"])
    settlement_files = list(log_dir.glob("settlement_manual_fetch_*.json"))
    
    if not settlement_files:
        print("❌ 未找到结账数据文件")
        return
    
    # 使用最新的文件
    latest_file = max(settlement_files, key=lambda f: f.stat().st_mtime)
    print(f"📂 检查文件: {latest_file.name}")
    
    # 读取数据
    with open(latest_file, "r", encoding="utf-8") as f:
        data = json.load(f)
    
    print(f"📊 文件顶层结构:")
    for key in data.keys():
        print(f"  - {key}: {type(data[key])}")
    
    records = data.get("records", [])
    print(f"\n📋 总记录数: {len(records)}")
    
    if not records:
        print("❌ 没有记录数据")
        return
    
    # 检查第一条记录的结构
    first_record = records[0]
    print(f"\n🔍 第一条记录的字段:")
    for key, value in first_record.items():
        value_type = type(value).__name__
        if isinstance(value, str) and len(value) > 50:
            value_preview = f"{value[:50]}..."
        else:
            value_preview = str(value)
        print(f"  - {key}: {value_type} = {value_preview}")
    
    # 查找时间相关字段
    time_fields = []
    for key, value in first_record.items():
        if isinstance(value, str) and any(pattern in key.lower() for pattern in ['time', 'date', '时间', '日期']):
            time_fields.append((key, value))
    
    if time_fields:
        print(f"\n🕐 时间相关字段:")
        for key, value in time_fields:
            print(f"  - {key}: {value}")
    else:
        print(f"\n❌ 未找到明显的时间字段")
    
    # 检查前几条记录，寻找时间模式
    print(f"\n🔍 前 5 条记录的所有字段值 (寻找时间模式):")
    for i, record in enumerate(records[:5]):
        print(f"\n记录 {i+1}:")
        for key, value in record.items():
            if isinstance(value, str) and len(value) > 10:
                # 检查是否像时间格式
                if any(char in str(value) for char in ['-', ':', ' ']) and any(char.isdigit() for char in str(value)):
                    print(f"  - {key}: {value} ⭐")
                else:
                    print(f"  - {key}: {value}")
            else:
                print(f"  - {key}: {value}")
    
    # 保存结构分析
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    analysis_file = log_dir / f"settlement_structure_analysis_{timestamp}.txt"
    
    with open(analysis_file, "w", encoding="utf-8") as f:
        f.write(f"结账数据结构分析\n")
        f.write(f"分析时间: {datetime.now().isoformat()}\n")
        f.write(f"数据文件: {latest_file.name}\n")
        f.write(f"总记录数: {len(records)}\n\n")
        
        f.write(f"第一条记录字段:\n")
        for key, value in first_record.items():
            f.write(f"  {key}: {type(value).__name__} = {str(value)[:100]}\n")
        
        if time_fields:
            f.write(f"\n时间相关字段:\n")
            for key, value in time_fields:
                f.write(f"  {key}: {value}\n")
    
    print(f"\n📋 结构分析已保存到: {analysis_file}")


if __name__ == "__main__":
    from datetime import datetime
    main()