#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""CEK DULU sebelum menakar laju publikasi artikel:
 1. URL Inspection API untuk 5 artikel baru (status indeks Google).
 2. Ringkasan cakupan indeks website (berapa URL terdaftar & terindeks).
 3. Pola publikasi website 30 hari terakhir (berapa artikel per hari) dari WP REST.
Read-only."""
import json, os, base64, urllib.request
from datetime import date, timedelta
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

WS = os.path.dirname(os.path.abspath(__file__))
t = json.load(open(os.path.join(WS, "seo-oauth", "google_token_atun.json")))
creds = Credentials(**{k: t[k] for k in ("token", "refresh_token", "token_uri",
                                         "client_id", "client_secret")}, scopes=t.get("scopes"))
sc = build("searchconsole", "v1", credentials=creds, cache_discovery=False)

SITE = "sc-domain:studiosoft.id"
BARU = ["https://studiosoft.id/jasa-seo-surabaya-paket-harga/",
        "https://studiosoft.id/tools-analisis-kompetitor-media-sosial/",
        "https://studiosoft.id/digital-agency-surabaya-vs-freelancer/",
        "https://studiosoft.id/branding-agency-surabaya-proses-hasil-kerja/",
        "https://studiosoft.id/jasa-maintenance-wordpress-pekerjaan-bulanan/"]

print("=== 1. URL INSPECTION 5 ARTIKEL BARU ===")
for u in BARU:
    try:
        r = sc.urlInspection().index().inspect(body={
            "inspectionUrl": u, "siteUrl": SITE, "languageCode": "id"}).execute()
        res = r.get("inspectionResult", {}).get("indexStatusResult", {})
        print(f"\n  {u}")
        print(f"    verdict      : {res.get('verdict')}")
        print(f"    coverage     : {res.get('coverageState')}")
        print(f"    robots       : {res.get('robotsTxtState')} | indexing: {res.get('indexingState')}")
        print(f"    terakhir crawl: {res.get('lastCrawlTime')}")
        print(f"    canonical    : {res.get('googleCanonical')}")
    except Exception as e:
        print(f"  {u} -> ERROR {str(e)[:200]}")

print("\n=== 2. SITEMAP ===")
try:
    sm = sc.sitemaps().list(siteUrl=SITE).execute()
    for s in sm.get("sitemap", []):
        print(f"  {s.get('path')} | tipe={s.get('type')} | isi={s.get('contents')} | error={s.get('errors')} "
              f"| warning={s.get('warnings')} | terakhir={s.get('lastDownloaded')}")
except Exception as e:
    print("  ERROR", str(e)[:200])

print("\n=== 3. POLA PUBLIKASI WEBSITE (WP REST, 40 artikel terakhir) ===")
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
r = urllib.request.Request("https://studiosoft.id/wp-json/wp/v2/posts?status=publish&per_page=60"
                           "&_fields=date,slug,author", headers=H)
d = json.loads(urllib.request.urlopen(r, timeout=120).read())
from collections import Counter
c = Counter(x["date"][:10] for x in d)
print("  tanggal        jumlah artikel")
for k in sorted(c, reverse=True)[:20]:
    print(f"  {k}     {c[k]}")
print("  catatan: hanya 60 artikel terakhir yang ditarik")
r2 = urllib.request.Request("https://studiosoft.id/wp-json/wp/v2/posts?status=future&per_page=30"
                            "&_fields=date,slug,status", headers=H)
try:
    f = json.loads(urllib.request.urlopen(r2, timeout=120).read())
    print(f"\n  artikel berstatus future: {len(f)}")
    for x in sorted(f, key=lambda y: y["date"])[:15]:
        print(f"    {x['date'][:16]}  {x['slug']}")
except Exception as e:
    print("  future error", str(e)[:120])
