#!/usr/bin/env python
# coding=utf-8
"""
Step5: 分析问题从什么时候开始 - ROS COPC 时间趋势
"""
import pandas as pd
from pathlib import Path
import glob

# 读取并合并数据
data_dir = Path(__file__).parent / "output" / "step5_时间趋势"
all_files = glob.glob(str(data_dir / "*.csv"))
df = pd.concat([pd.read_csv(f) for f in all_files], ignore_index=True)
df = df.sort_values('dt')

print("=" * 70)
print("Step5: ROS COPC 时间趋势分析")
print("=" * 70)

# 1. 数据概览
print("\n【1. 数据概览】")
print(f"日期范围: {df['dt'].min()} ~ {df['dt'].max()}")
print(f"天数: {len(df)}")

# 2. 时间趋势
print("\n【2. ROS COPC 时间趋势】")
print(f"{'日期':<12} {'预估ROS':>10} {'真实ROS':>10} {'COPC':>8} {'偏差':>10}")
print("-" * 55)
for _, row in df.iterrows():
    bias = (1 - row['ros_copc']) * 100 if pd.notna(row['ros_copc']) else 0
    copc = row['ros_copc'] if pd.notna(row['ros_copc']) else 0
    print(f"{int(row['dt']):<12} {row['pred_ros']:>10.4f} {row['real_ros']:>10.4f} {copc:>8.4f} {bias:>+9.1f}%")

# 3. 分段统计
print("\n【3. 分段统计】")
df['week'] = pd.to_datetime(df['dt'].astype(str)).dt.isocalendar().week
weekly = df.groupby('week').agg({
    'pred_ros': 'mean',
    'real_ros': 'mean',
    'ros_copc': 'mean'
}).round(4)
weekly['偏差%'] = ((1 - weekly['ros_copc']) * 100).round(1)
print(weekly.to_string())

# 4. 找拐点
print("\n【4. 趋势分析】")
df['bias_pct'] = (1 - df['ros_copc']) * 100

# 计算滚动平均
df['bias_ma3'] = df['bias_pct'].rolling(3, min_periods=1).mean()

# 找最大偏差时间点
max_bias_idx = df['bias_pct'].idxmax()
max_bias_date = df.loc[max_bias_idx, 'dt']
max_bias_val = df.loc[max_bias_idx, 'bias_pct']

min_bias_idx = df['bias_pct'].idxmin()
min_bias_date = df.loc[min_bias_idx, 'dt']
min_bias_val = df.loc[min_bias_idx, 'bias_pct']

print(f"最大偏差: {int(max_bias_date)} ({max_bias_val:+.1f}%)")
print(f"最小偏差: {int(min_bias_date)} ({min_bias_val:+.1f}%)")

# 前后对比
first_week = df.head(7)['bias_pct'].mean()
last_week = df.tail(7)['bias_pct'].mean()
print(f"\n前7天平均偏差: {first_week:+.1f}%")
print(f"后7天平均偏差: {last_week:+.1f}%")

# 5. 结论
print("\n" + "=" * 70)
print("【Step5 结论】")
print("=" * 70)
if last_week > first_week + 5:
    print(f"问题在恶化: 偏差从 {first_week:+.1f}% 上升到 {last_week:+.1f}%")
elif last_week < first_week - 5:
    print(f"问题在改善: 偏差从 {first_week:+.1f}% 下降到 {last_week:+.1f}%")
else:
    print(f"问题一直存在: 偏差稳定在 {df['bias_pct'].mean():+.1f}% 左右")

# 保存结果
output_dir = Path(__file__).parent / "output"
df.to_csv(output_dir / "step5_时间趋势_合并.csv", index=False)

with open(output_dir / "step5_结论.txt", 'w', encoding='utf-8') as f:
    f.write("=" * 70 + "\n")
    f.write("Step5: ROS COPC 时间趋势\n")
    f.write("=" * 70 + "\n\n")
    f.write(f"日期范围: {df['dt'].min()} ~ {df['dt'].max()}\n")
    f.write(f"平均偏差: {df['bias_pct'].mean():+.1f}%\n")
    f.write(f"前7天: {first_week:+.1f}%\n")
    f.write(f"后7天: {last_week:+.1f}%\n")

print(f"\n结果已保存到 output/ 目录")
