#!/usr/bin/env python3
"""Scan semua post studiosoft.id — cek status Yoast (SEO analysis) tiap post."""
import requests, json, sys, time

WP = 'https://studiosoft.id/wp-json/wp/v2'
USER = 'bambangbot'
APP_PASS = 'q26r RePo BVy6 pwU2 F3z7 ouyl'
OUT = '/home/mantapman/.hermes/profiles/atun/workspace/ss_yoast_scan_result.json'

posts = []
page = 1
while True:
    try:
        r = requests.get(f'{WP}/posts', auth=(USER, APP_PASS),
                         params={'per_page': 100, 'page': page,
                                 'status': 'publish,draft,pending',
                                 '_fields': 'id,title,status,slug,modified,meta'}, timeout=60)
    except Exception as e:
        print(f'ERR page {page}: {e}', file=sys.stderr); break
    if r.status_code != 200:
        break
    d = r.json()
    if not d:
        break
    posts += d
    if len(d) < 100:
        break
    page += 1

print(f'Total fetched: {len(posts)}', flush=True)

def m(p, key):
    v = (p.get('meta') or {}).get(key, '')
    return (v or '').strip()

rows = []
for p in posts:
    focus = m(p, '_yoast_wpseo_focuskw')
    metadesc = m(p, '_yoast_wpseo_metadesc')
    title_ov = m(p, '_yoast_wpseo_title')
    score = m(p, '_yoast_wpseo_content_score')  # 0-100 score, 0 = belum dianalisis?
    score_inc = m(p, '_yoast_wpseo_linkdex')    # readability? often linkdex = SEO score
    rows.append({
        'id': p['id'],
        'title': (p['title'] or {}).get('rendered', '')[:80],
        'status': p['status'],
        'slug': p['slug'],
        'modified': p['modified'],
        'focus': focus,
        'metadesc': metadesc,
        'titleseo': title_ov,
        'content_score': score,
        'linkdex': score_inc,
    })

with open(OUT, 'w') as f:
    json.dump(rows, f, indent=2, ensure_ascii=False)

# Ringkasan
n = len(rows)
no_focus = [r for r in rows if not r['focus']]
no_meta = [r for r in rows if not r['metadesc']]
no_score = [r for r in rows if not r['content_score'] and not r['linkdex']]
print(f"\n=== RINGKASAN ===")
print(f"Total post: {n}")
print(f"Belum ada focus keyword (belum di-Analyze): {len(no_focus)}")
print(f"Belum ada meta desc: {len(no_meta)}")
print(f"Belum ada SEO score (content_score/linkdex kosong): {len(no_score)}")
print(f"\nDaftar yg belum dianalisis (focus kosong):")
for r in no_focus[:60]:
    print(f"  ID {r['id']} [{r['status']}] {r['title']}")
if len(no_focus) > 60:
    print(f"  ... dan {len(no_focus)-60} lainnya")
print(f"\nHasil lengkap: {OUT}")
