#!/usr/bin/env python3
"""Full we-mp-rss diagnostic: login, feeds, articles, browser, Redis.
Usage: ~/project/we-mp-rss-main/venv/bin/python3 check_werss_full.py
"""
import sqlite3, os, redis, json
from datetime import datetime

DB = '/home/ubuntu/project/we-mp-rss-data/db.db'

print("=" * 50)
print("we-mp-rss 完整诊断")
print("=" * 50)

# 1. Redis login status
print("\n--- Redis ---")
try:
    r = redis.from_url('redis://localhost:6379', decode_responses=True)
    status = r.get('werss:login:status')
    print(f"  login_status: {status} {'✅' if status == '1' else '❌'}")
    
    article_info = r.get('werss:article:info')
    if article_info:
        d = json.loads(article_info)
        print(f"  article_info: all={d.get('all_count',0)} mp={d.get('mp_all_count',0)}")
    
    queue = r.hgetall('werss:queue:status')
    if queue:
        print(f"  queue: running={queue.get(b'is_running',b'?').decode()} pending={queue.get(b'pending_count',b'?').decode()}")
except Exception as e:
    print(f"  Redis ERROR: {e}")

# 2. Database
print("\n--- Database ---")
try:
    db = sqlite3.connect(DB)
    total = db.execute("SELECT COUNT(*) FROM articles").fetchone()[0]
    latest = db.execute("SELECT MAX(created_at) FROM articles").fetchone()[0]
    print(f"  Articles: {total} total, latest: {latest}")
    
    print("  Feeds:")
    for row in db.execute("SELECT mp_name, status, updated_at FROM feeds"):
        print(f"    {row[0]}: status={row[1]} {'✅' if row[1]==1 else '❌(disabled)'} updated={row[2]}")
    
    print("  Per-feed latest:")
    for row in db.execute(
        "SELECT f.mp_name, MAX(a.created_at), COUNT(*) FROM articles a JOIN feeds f ON a.mp_id=f.id GROUP BY f.mp_name"
    ):
        print(f"    {row[0]}: {row[2]} articles, latest={row[1]}")
    
    db.close()
except Exception as e:
    print(f"  DB ERROR: {e}")

# 3. Browser
print("\n--- Browser ---")
cache = os.path.expanduser("~/.cache/ms-playwright")
if os.path.exists(cache):
    browsers = [d for d in os.listdir(cache) if d.startswith('chromium') or d.startswith('firefox')]
    print(f"  Playwright cache: {browsers}")
else:
    print("  No Playwright cache")
