#!/usr/bin/env python
# coding=utf-8
"""
Step3d: 分析 ROS 与推荐天数的关系
"""
import pandas as pd
from pathlib import Path

# 读取 step2 数据（有推荐天数间隔字段）
data_file = Path(__file__).parent / "output" / "step2_影响面_20260101_20260113.csv"
df = pd.read_csv(data_file)

print("=" * 70)
print("Step3d: ROS 与推荐天数的关系")
print("=" * 70)

# 1. 数据概览
print("\n【1. 数据概览】")
print(f"样本数: {len(df)} 条")
print(f"推荐天数范围: {df['推荐天数间隔'].min()} ~ {df['推荐天数间隔'].max()}")

# 2. 按推荐天数分组看 ros
print("\n【2. 按推荐天数分组看 ROS】")
df['天数分组'] = pd.cut(df['推荐天数间隔'], bins=[-1, 3, 7, 14, 30, 1000],
                       labels=['0-3天', '4-7天', '8-14天', '15-30天', '>30天'])
group_day = df.groupby('天数分组', observed=True).agg({
    'ros_t0': ['mean', 'std'],
    'vov0': 'mean',
    'exp': 'sum',
    'vid': 'count'
}).round(4)
group_day.columns = ['ROS均值', 'ROS标准差', 'VOV均值', '总曝光', '视频数']
print(group_day.to_string())

# 3. 问题视频的推荐天数分布
print("\n【3. 问题视频的推荐天数分布】")
# 定义问题视频（vov0 < 中位数 且 曝光rank <= 10）
median_vov = df['vov0'].median()
problem_df = df[(df['曝光rank'] <= 10) & (df['vov0'] < median_vov)]
print(f"问题视频数: {len(problem_df)}")

if len(problem_df) > 0:
    problem_day = problem_df.groupby('天数分组', observed=True).agg({
        'ros_t0': 'mean',
        'vov0': 'mean',
        'vid': 'count'
    }).round(4)
    problem_day.columns = ['ROS均值', 'VOV均值', '视频数']
    print(problem_day.to_string())

# 4. 对比新视频 vs 老视频
print("\n【4. 新视频 vs 老视频对比】")
new_videos = df[df['推荐天数间隔'] <= 7]
old_videos = df[df['推荐天数间隔'] > 30]
print(f"新视频(<=7天): ROS={new_videos['ros_t0'].mean():.4f}, VOV={new_videos['vov0'].mean():.4f}, 数量={len(new_videos)}")
print(f"老视频(>30天): ROS={old_videos['ros_t0'].mean():.4f}, VOV={old_videos['vov0'].mean():.4f}, 数量={len(old_videos)}")

# 5. 结论
print("\n" + "=" * 70)
print("【Step3d 结论】")
print("=" * 70)
new_ros = new_videos['ros_t0'].mean()
old_ros = old_videos['ros_t0'].mean()
if new_ros > old_ros:
    print(f"新视频 ROS ({new_ros:.4f}) > 老视频 ROS ({old_ros:.4f})")
    print(f"ROS 随推荐天数增加而下降 (衰减 {(1-old_ros/new_ros)*100:.1f}%)")
else:
    print(f"新视频 ROS ({new_ros:.4f}) <= 老视频 ROS ({old_ros:.4f})")
    print("ROS 没有随推荐天数明显衰减")

# 保存结论
output_dir = Path(__file__).parent / "output"
with open(output_dir / "step3d_结论.txt", 'w', encoding='utf-8') as f:
    f.write("=" * 70 + "\n")
    f.write("Step3d: ROS 与推荐天数的关系\n")
    f.write("=" * 70 + "\n\n")
    f.write(f"新视频(<=7天): ROS={new_ros:.4f}\n")
    f.write(f"老视频(>30天): ROS={old_ros:.4f}\n")
    if new_ros > old_ros:
        f.write(f"结论: ROS 随推荐天数增加而下降\n")

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