#!/usr/bin/env python3
"""TSLaw: daftarkan ulang sitemap_index.xml ke Search Console + bersihkan entri sitemap yang basi."""
import json, urllib.parse, urllib.request, urllib.error

TOKEN = "/home/mantapman/.hermes/profiles/atun/workspace/seo-oauth/google_token_atun.json"
SITE = "https://www.tslaw.id/"
SITE_ENC = urllib.parse.quote(SITE, safe="")

from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
c = Credentials.from_authorized_user_file(TOKEN)
if c.expired and c.refresh_token:
    c.refresh(Request()); open(TOKEN, "w").write(c.to_json())
H = {"Authorization": f"Bearer {c.token}"}


def panggil(u, metode="GET"):
    r = urllib.request.Request(u, headers=H, method=metode)
    try:
        with urllib.request.urlopen(r, timeout=120) as x:
            isi = x.read().decode("utf-8", "replace")
            return x.status, (json.loads(isi) if isi.strip() else {})
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:300]
    except Exception as e:
        return 0, str(e)[:150]


print("=== daftar sitemap SEBELUM ===")
st, d = panggil(f"https://www.googleapis.com/webmasters/v3/sites/{SITE_ENC}/sitemaps")
sebelum = [s["path"] for s in (d.get("sitemap") or [])] if isinstance(d, dict) else []
for p in sebelum:
    print("   ", p)

print("\n=== daftarkan sitemap utama ===")
for feed in ("https://www.tslaw.id/sitemap_index.xml",
             "https://www.tslaw.id/post-sitemap.xml",
             "https://www.tslaw.id/page-sitemap.xml"):
    feed_enc = urllib.parse.quote(feed, safe="")
    st, d = panggil(f"https://www.googleapis.com/webmasters/v3/sites/{SITE_ENC}/sitemaps/{feed_enc}", "PUT")
    print(f"   {feed.replace('https://www.tslaw.id', ''):<26} status {st} | {str(d)[:120]}")

print("\n=== hapus entri basi (author-sitemap sudah dimatikan) ===")
feed_enc = urllib.parse.quote("https://www.tslaw.id/author-sitemap.xml", safe="")
st, d = panggil(f"https://www.googleapis.com/webmasters/v3/sites/{SITE_ENC}/sitemaps/{feed_enc}", "DELETE")
print(f"   author-sitemap.xml → status {st} | {str(d)[:150]}")

print("\n=== daftar sitemap SESUDAH ===")
st, d = panggil(f"https://www.googleapis.com/webmasters/v3/sites/{SITE_ENC}/sitemaps")
if isinstance(d, dict):
    for s in (d.get("sitemap") or []):
        isi = (s.get("contents") or [{}])[0]
        print(f"   {s['path'].replace('https://www.tslaw.id', ''):<26} unduh terakhir {s.get('lastDownloaded','-')[:10]} | "
              f"dikirim {isi.get('submitted','?')} | error {s.get('errors',0)} | warning {s.get('warnings',0)}")
else:
    print("   ", str(d)[:200])
