#!/bin/bash
LOG="/var/www/audio/stats/play.log"
OUT="/var/www/audio/stats"

python3 - <<'PY' "$LOG" "$OUT"
import sys, json, datetime, collections
log_path, out_dir = sys.argv[1], sys.argv[2]
today = datetime.date.today().strftime('%Y-%m-%d')
d = datetime.date.today()
week  = f'{d:%Y}-W{d:%V}'
month = d.strftime('%Y-%m')
year  = d.strftime('%Y')

def agg(scope=None, value=None):
    cnt = collections.Counter()
    try:
        with open(log_path, 'r', encoding='utf-8') as f:
            for line in f:
                parts = line.strip().split('|')
                if len(parts) < 8: 
                    continue
                date_only, week_s, month_s, year_s = parts[1], parts[2], parts[3], parts[4]
                audio_id, name = parts[5], parts[6]
                if scope == 'day'   and date_only != value:  continue
                if scope == 'week'  and week_s   != value:   continue
                if scope == 'month' and month_s  != value:   continue
                if scope == 'year'  and year_s   != value:   continue
                cnt[(audio_id, name)] += 1
    except FileNotFoundError:
        pass
    arr = [{'id': int(i) if str(i).isdigit() else i, 'name': n, 'count': c}
           for (i, n), c in cnt.most_common()]
    return json.dumps(arr, ensure_ascii=False)

open(f'{out_dir}/query_day.json',   'w', encoding='utf-8').write(agg('day',   today))
open(f'{out_dir}/query_week.json',  'w', encoding='utf-8').write(agg('week',  week))
open(f'{out_dir}/query_month.json', 'w', encoding='utf-8').write(agg('month', month))
open(f'{out_dir}/query_year.json',  'w', encoding='utf-8').write(agg('year',  year))
PY

chmod 644 /var/www/audio/stats/query_*.json 2>/dev/null || true
chown nginx:nginx /var/www/audio/stats/query_*.json 2>/dev/null || true
