#!/usr/bin/env python3
"""Cek status index sampel artikel yang nol impresi (GSC URL Inspection)."""
import json, os, time, urllib.request
from google.auth.transport.requests import Request
from google.oauth2 import service_account

data = json.load(open("ss_nol_impresi.json"))
nol = data["nol_impresi"]
creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/webmasters.readonly"])
creds.refresh(Request())
S = "https://studiosoft.id/"

# ambil sampel: 6 terbaru, 6 dari pita 60-120 hari, 6 terlama
sampel = nol[:6] + nol[20:26] + nol[-6:]
print(f"memeriksa {len(sampel)} artikel (dari {len(nol)} yang nol impresi)\n")
from collections import Counter
stat = Counter()
for x in sampel:
    body = json.dumps({"inspectionUrl": x["link"], "siteUrl": S}).encode()
    req = urllib.request.Request("https://searchconsole.googleapis.com/v1/urlInspection/index:inspect", data=body,
                                 headers={"Authorization": f"Bearer {creds.token}", "Content-Type": "application/json"})
    try:
        res = json.load(urllib.request.urlopen(req, timeout=60))
        st = res["inspectionResult"]["indexStatusResult"]
        status = st.get("coverageState")
        stat[status] += 1
        print(f"  {status:<34} | crawl {str(st.get('lastCrawlTime'))[:10]:<11} | {x['kata']:>4} kata | {x['judul'][:44]}")
    except Exception as e:
        stat["ERROR"] += 1
        print(f"  ERROR {str(e)[:40]} | {x['judul'][:44]}")
    time.sleep(0.3)
print("\nringkasan:", dict(stat))
