#!/usr/bin/env python
# coding=utf-8
"""
渠道用户量统计
按人数（UV）统计各渠道及素材字段覆盖情况
"""
import pandas as pd
from pathlib import Path

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

csv_files = [f for f in output_dir.glob("*.csv") if '_分析' not in f.name]
if not csv_files:
    print("没有找到数据文件，请先运行 query.sql")
    exit(1)

latest_file = max(csv_files, key=lambda x: x.stat().st_mtime)
df = pd.read_csv(latest_file)

lines = []


def log(text=""):
    print(text)
    lines.append(text)


log(f"分析文件: {latest_file.name}")
log()

log("=" * 80)
log("各渠道用户量及素材覆盖")
log("=" * 80)
log()

header = f"{'渠道':<25} {'用户数':>10} {'人均点击':>8} {'文章标题':>10} {'卡片标题':>10}"
log(header)
log("-" * 80)

for _, row in df.iterrows():
    ch = row['channel']
    uv = int(row['用户数'])
    pv = int(row['点击数'])
    avg = pv / uv if uv > 0 else 0
    art = row['有文章标题用户'] / uv if uv > 0 else 0
    card = row['有卡片标题用户'] / uv if uv > 0 else 0
    log(f"{ch:<25} {uv:>10,} {avg:>8.1f} {art:>10.0%} {card:>10.0%}")

log()

# 汇总
total_uv = df['用户数'].sum()
total_pv = df['点击数'].sum()
log("=" * 80)
log("汇总")
log("=" * 80)
log(f"总用户数: {int(total_uv):,}")
log(f"总点击数: {int(total_pv):,}")
log(f"人均点击: {total_pv/total_uv:.1f}")
log()

# 保存
result_file = output_dir / f"{latest_file.stem}_分析.txt"
with open(result_file, 'w', encoding='utf-8') as f:
    f.write("\n".join(lines))
log(f"结果已保存: {result_file}")
