#!/usr/bin/env python3
"""DAS Bengkel — pemeriksaan teknis: status index halaman uang, kecepatan respons, robots & sitemap."""
import json, os, time, urllib.request, urllib.error
from datetime import date, timedelta

from google.auth.transport.requests import Request
from google.oauth2 import service_account

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
SITE = "https://dasindonesia.com/"
DOM = "dasindonesia.com"
UA = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}

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())

HALAMAN = [
    "https://dasindonesia.com/",
    "https://dasindonesia.com/bengkel-spesialis-nissan-surabaya/",
    "https://dasindonesia.com/bengkel-spesialis-matic-surabaya/",
    "https://dasindonesia.com/bengkel-spesialis-lexus-di-surabaya/",
    "https://dasindonesia.com/bengkel-spesialis-alphard-surabaya/",
    "https://dasindonesia.com/bengkel-spesialis-overhaul-mobil-surabaya-kapan-dibutuhkan/",
    "https://dasindonesia.com/bengkel-mobil-toyota-camry-surabaya-panduan-perawatan/",
    "https://dasindonesia.com/ev-diagnostic/",
]

print("=== 1. status index (GSC URL Inspection) ===")
for u in HALAMAN:
    body = json.dumps({"inspectionUrl": u, "siteUrl": SITE}).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))
        idx = res.get("inspectionResult", {}).get("indexStatusResult", {})
        print(f"   {idx.get('coverageState', '?'):<32} | crawl {str(idx.get('lastCrawlTime'))[:10]} | "
              f"verdict {idx.get('verdict', '?')} | {u.replace('https://dasindonesia.com', '')[:56]}")
    except urllib.error.HTTPError as e:
        print(f"   HTTP {e.code} | {u[:60]}")
    time.sleep(0.4)

print("\n=== 2. kecepatan respons (permintaan pertama, seperti bot) ===")
for u in HALAMAN[:5] + [f"{SITE}sitemap_index.xml", f"{SITE}robots.txt"]:
    t0 = time.time()
    try:
        r = urllib.request.Request(u, headers=UA)
        with urllib.request.urlopen(r, timeout=90) as x:
            x.read(2048)
            kode = x.status
            cf = x.headers.get("cf-cache-status", "-")
            age = x.headers.get("age", "-")
    except urllib.error.HTTPError as e:
        kode, cf, age = e.code, "-", "-"
    except Exception as e:
        print(f"   ❌ {u[:70]} — {str(e)[:50]}")
        continue
    print(f"   {time.time() - t0:>5.2f}s | HTTP {kode} | cf {cf:<8} | age {age:<6} | {u.replace(SITE, '/')[:52]}")
    time.sleep(1)

print("\n=== 3. robots.txt & sitemap ===")
try:
    with urllib.request.urlopen(urllib.request.Request(f"{SITE}robots.txt", headers=UA), timeout=60) as x:
        print("   robots.txt:")
        for b in x.read().decode("utf-8", "replace").splitlines()[:12]:
            print(f"     {b}")
except Exception as e:
    print("   robots gagal:", str(e)[:60])
try:
    with urllib.request.urlopen(urllib.request.Request(f"{SITE}sitemap_index.xml", headers=UA), timeout=60) as x:
        t = x.read().decode("utf-8", "replace")
    print(f"   sitemap_index.xml: {len(t)} char · berisi {t.count('<loc>')} entri")
except Exception as e:
    print("   sitemap gagal:", str(e)[:60])

print("\n=== 4. jumlah artikel terbit per bulan (pola menerbitkan) ===")
import base64
h = {"Authorization": "Basic " + base64.b64encode(b"bambangbot:" + json.load(open(f"{WS}/.das_pass.json"))["pass"].encode()).decode(),
     **UA} if os.path.exists(f"{WS}/.das_pass.json") else None
