#!/usr/bin/env python
# coding=utf-8
"""
Step9: 天级数据和趋势线分析
"""
import pandas as pd
import numpy as np
from pathlib import Path

output_dir = Path(__file__).parent / "output"

# 读取180天数据
df = pd.read_csv(output_dir / "step7_头部vov趋势_合并.csv")
df = df.sort_values('dt').reset_index(drop=True)
df['date'] = pd.to_datetime(df['dt'].astype(str))

print("=" * 80)
print("Step9: 天级数据和趋势线分析")
print("=" * 80)

# 1. 12月-1月详细数据
print("\n【1. 12月-1月 天级数据】")
df_recent = df[df['dt'] >= 20251201].copy()

print(f"{'日期':<10} {'vov均值':>8} {'str':>8} {'ros':>6} {'vor':>6} {'问题%':>8} {'趋势':>6}")
print("-" * 60)

# 计算7日滚动平均
df_recent['problem_ma7'] = df_recent['problem_pct'].rolling(7, min_periods=1).mean()
df_recent['vov_ma7'] = df_recent['vov_mean'].rolling(7, min_periods=1).mean()

prev_problem = None
for _, row in df_recent.iterrows():
    trend = ""
    if prev_problem is not None:
        if row['problem_pct'] > prev_problem + 5:
            trend = "↑↑"
        elif row['problem_pct'] > prev_problem:
            trend = "↑"
        elif row['problem_pct'] < prev_problem - 5:
            trend = "↓↓"
        elif row['problem_pct'] < prev_problem:
            trend = "↓"
        else:
            trend = "→"
    prev_problem = row['problem_pct']

    print(f"{int(row['dt']):<10} {row['vov_mean']:>8.4f} {row['str_mean']:>8.4f} "
          f"{row['ros_mean']:>6.2f} {row['vor_mean']:>6.2f} {row['problem_pct']:>7.1f}% {trend:>6}")

# 2. 趋势线（文字图表）
print("\n【2. 问题比例趋势线（12月-1月）】")
print("日期        0%    10%   20%   30%   40%   50%")
print("           |-----|-----|-----|-----|-----|")

for _, row in df_recent.iterrows():
    bar_len = int(row['problem_pct'] / 2)  # 每2%一个字符
    bar = "█" * bar_len
    ma_pos = int(row['problem_ma7'] / 2)

    date_str = str(int(row['dt']))
    print(f"{date_str}   {bar:<25} {row['problem_pct']:.0f}%")

# 3. vov 趋势线
print("\n【3. vov 均值趋势线（12月-1月）】")
print("日期       0.2   0.3   0.4   0.5   0.6   0.7")
print("           |-----|-----|-----|-----|-----|")

for _, row in df_recent.iterrows():
    # vov 范围 0.2-0.7，映射到 0-25 个字符
    bar_len = int((row['vov_mean'] - 0.2) / 0.02)
    bar_len = max(0, min(25, bar_len))
    bar = "█" * bar_len

    date_str = str(int(row['dt']))
    print(f"{date_str}   {bar:<25} {row['vov_mean']:.2f}")

# 4. 关键时间点分析
print("\n【4. 关键时间点分析】")

# 找问题比例的拐点
df_recent['problem_diff'] = df_recent['problem_pct'].diff()

# 找最大下降点
min_diff_idx = df_recent['problem_diff'].idxmin()
if pd.notna(min_diff_idx):
    row = df_recent.loc[min_diff_idx]
    print(f"问题比例最大下降: {int(row['dt'])} (下降 {row['problem_diff']:.1f}%)")

# 找最大上升点
max_diff_idx = df_recent['problem_diff'].idxmax()
if pd.notna(max_diff_idx):
    row = df_recent.loc[max_diff_idx]
    print(f"问题比例最大上升: {int(row['dt'])} (上升 {row['problem_diff']:.1f}%)")

# 5. 12月 vs 1月 分段对比
print("\n【5. 12月 vs 1月 对比】")
dec = df_recent[df_recent['dt'] < 20260101]
jan = df_recent[df_recent['dt'] >= 20260101]

print(f"\n{'指标':<12} {'12月均值':>12} {'1月均值':>12} {'变化':>12}")
print("-" * 50)
for col, name in [('vov_mean', 'vov'), ('str_mean', 'str'), ('ros_mean', 'ros'),
                  ('vor_mean', 'vor'), ('problem_pct', '问题比例%')]:
    dec_val = dec[col].mean()
    jan_val = jan[col].mean()
    if dec_val != 0:
        change = (jan_val - dec_val) / dec_val * 100
        print(f"{name:<12} {dec_val:>12.4f} {jan_val:>12.4f} {change:>+11.1f}%")

# 6. 周度汇总
print("\n【6. 周度汇总】")
df_recent['week'] = df_recent['date'].dt.isocalendar().week
df_recent['year'] = df_recent['date'].dt.year

weekly = df_recent.groupby(['year', 'week']).agg({
    'dt': ['min', 'max', 'count'],
    'vov_mean': 'mean',
    'str_mean': 'mean',
    'ros_mean': 'mean',
    'vor_mean': 'mean',
    'problem_pct': 'mean'
}).round(4)

print(f"{'周':<10} {'日期范围':<20} {'天数':>4} {'vov':>8} {'str':>8} {'问题%':>8}")
print("-" * 65)
for (year, week), row in weekly.iterrows():
    start = int(row[('dt', 'min')])
    end = int(row[('dt', 'max')])
    days = int(row[('dt', 'count')])
    vov = row[('vov_mean', 'mean')]
    str_v = row[('str_mean', 'mean')]
    prob = row[('problem_pct', 'mean')]
    print(f"{year}-W{week:<4} {start}-{end:<12} {days:>4} {vov:>8.4f} {str_v:>8.4f} {prob:>7.1f}%")

# 7. 结论
print("\n" + "=" * 80)
print("【Step9 结论】")
print("=" * 80)

dec_prob = dec['problem_pct'].mean()
jan_prob = jan['problem_pct'].mean()
change = jan_prob - dec_prob

print(f"\n12月平均问题比例: {dec_prob:.1f}%")
print(f"1月平均问题比例: {jan_prob:.1f}%")
print(f"变化: {change:+.1f}%")

if change > 5:
    print(f"\n⚠️  1月问题回升明显，需要关注")

    # 找原因
    dec_str = dec['str_mean'].mean()
    jan_str = jan['str_mean'].mean()
    str_change = (jan_str - dec_str) / dec_str * 100

    dec_vor = dec['vor_mean'].mean()
    jan_vor = jan['vor_mean'].mean()
    vor_change = (jan_vor - dec_vor) / dec_vor * 100

    print(f"\n原因分析:")
    print(f"  STR 变化: {str_change:+.1f}%")
    print(f"  VOR 变化: {vor_change:+.1f}%")

# 保存天级数据
df_recent.to_csv(output_dir / "step9_天级数据_12月1月.csv", index=False)
print(f"\n结果已保存到 output/ 目录")
