#!/usr/bin/env python3
"""Cek dampak perubahan URL TSLaw lewat GSC: format URL yang diindeks Google dan tayangannya."""
import os
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

SITE = "https://www.tslaw.id/"
creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/webmasters.readonly"])
gsc = build("webmasters", "v3", credentials=creds, cache_discovery=False)
AKHIR = date.today() - timedelta(days=2)
AWAL = AKHIR - timedelta(days=89)

tot = gsc.searchanalytics().query(siteUrl=SITE, body={
    "startDate": AWAL.isoformat(), "endDate": AKHIR.isoformat()}).execute().get("rows", [])
if tot:
    x = tot[0]
    print(f"90 hari: {int(x['clicks'])} klik · {int(x['impressions'])} tayangan · posisi {x['position']:.1f}")

print("\n=== 12 halaman dengan tayangan terbanyak (format URL-nya) ===")
rows = gsc.searchanalytics().query(siteUrl=SITE, body={
    "startDate": AWAL.isoformat(), "endDate": AKHIR.isoformat(), "dimensions": ["page"],
    "rowLimit": 50}).execute().get("rows", [])
htm = non = 0
for r in sorted(rows, key=lambda y: -y["impressions"])[:12]:
    u = r["keys"][0].replace("https://www.tslaw.id", "")
    tanda = ".htm" if u.endswith(".htm") else ""
    print(f"   {int(r['impressions']):>5} tayang | {int(r['clicks']):>3} klik | pos {r['position']:>5.1f} | {u[-62:]} {tanda}")
for r in rows:
    if r["keys"][0].rstrip("/").endswith(".htm"):
        htm += 1
    else:
        non += 1
print(f"\n   halaman format .htm: {htm} · tanpa .htm: {non}")

print("\n=== 7 hari terakhir vs sebelumnya (apakah tayangan jatuh) ===")
for label, a, b in (("7 hari terakhir", AKHIR - timedelta(days=6), AKHIR),
                    ("7 hari sebelumnya", AKHIR - timedelta(days=13), AKHIR - timedelta(days=7))):
    t = gsc.searchanalytics().query(siteUrl=SITE, body={
        "startDate": a.isoformat(), "endDate": b.isoformat()}).execute().get("rows", [])
    if t:
        print(f"   {label}: {int(t[0]['clicks'])} klik · {int(t[0]['impressions'])} tayangan · pos {t[0]['position']:.1f}")
