# -*- coding: utf-8 -*-
import json, os, datetime
os.chdir(os.path.dirname(os.path.abspath(__file__)))
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')

def load(fn):
    with open(os.path.join('data', fn), encoding='utf-8') as f:
        return json.load(f)

print('== 时间戳核查（应全部=实时 %s）==' % now)
issues = []
hw = load('hot_words.json')
og = load('opportunity_goods.json')
ss = load('store_stats.json')
for k, v in [('hot_words.collected_at', hw.get('collected_at')), ('opportunity.collected_at', og.get('collected_at')),
             ('store_stats.generated_at', ss.get('generated_at'))]:
    print(' ', k, '=', v, 'OK' if v else 'MISSING')
    if not v: issues.append(k)

print('== 数据量核查 ==')
print(' hot_words.words:', len(hw.get('words', [])))
print(' theme_freqs keys:', list(hw.get('theme_freqs', {}).keys()))
print(' scene_words:', len(hw.get('scene_words', [])))
print(' consumer_search hot/short:', (hw.get('consumer_search') or {}).get('hot_count'), '/', (hw.get('consumer_search') or {}).get('short_count'))
print(' goods.total:', og.get('total'), 'raw:', og.get('raw_records'))
print(' recs:', len(og.get('recs', [])))
print(' cs_pools:', {k: {'raw': v['raw'], 'relevant': v['relevant']} for k, v in og.get('cs_pools', {}).items()})
print(' sales_sample:', og.get('sales_sample', {}).get('table_total'), 'rows, relevant', og.get('sales_sample', {}).get('relevant'))
print(' expo_click hi/lo:', len(og.get('expo_click_groups', {}).get('hi_expo_lo_ctr', [])), '/', len(og.get('expo_click_groups', {}).get('lo_expo_hi_ctr', [])))
print(' blue_ocean:', og.get('blue_ocean_words'))
print(' seg_blue_candidates:', len(og.get('seg_blue_candidates', [])))
print(' trend_alerts:', og.get('trend_alerts'))

print('== 热搜词TOP12 ==')
for w in hw.get('words', [])[:12]:
    print(' ', w['word'], 'score', w['score'], 'freq', w['freq'], w['comp_tier'], 'blue' if w.get('blue_ocean') else '', 'trend', w.get('trend', {}).get('note', ''))

print('== 推荐新品TOP6 ==')
for r in og.get('recs', [])[:6]:
    print(' ', r['name'][:30], '¥'+str(r['price']), r['cat'], 'w'+str(r['weight']), 'sales', r.get('sales_txt', '-'))

print('== 归档检查 ==')
hist = os.path.join('_scrape', '历史')
if os.path.exists(hist):
    days = sorted(os.listdir(hist))
    print(' 历史目录:', days)
    latest = os.path.join(hist, days[-1]) if days else None
    if latest:
        print(' 最新', days[-1], '文件数:', len(os.listdir(latest)))
print('== 服务 ==')
try:
    import urllib.request
    r = urllib.request.urlopen('http://127.0.0.1:8000/dashboard.html', timeout=5)
    print(' 看板HTTP:', r.status, r.headers.get('Cache-Control'))
except Exception as ex:
    print(' 看板服务异常:', ex)
