#!/usr/bin/env python3
"""The Skin Code Clinic: tarik data GSC + GA4 (28 & 90 hari) + kondisi situs."""
import os, re, time, urllib.request, urllib.error

KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
from google.oauth2 import service_account
from googleapiclient.discovery import build

SC = ["https://www.googleapis.com/auth/webmasters.readonly"]
gsc = build("searchconsole", "v1", credentials=service_account.Credentials.from_service_account_file(KEY, scopes=SC),
            cache_discovery=False)

print("=== properti yang cocok 'skin' ===")
for s in gsc.sites().list().execute().get("siteEntry", []):
    if "skin" in s["siteUrl"].lower():
        print(f"   {s['siteUrl']:<46} {s.get('permissionLevel')}")

SITE = "https://www.theskincodeclinic.com/"
print(f"\n=== GSC {SITE} ===")
for label, mulai, akhir in (("28 hari", "2026-08-29", "2026-09-25"), ("90 hari", "2026-06-28", "2026-09-25")):
    try:
        rows = gsc.searchanalytics().query(siteUrl=SITE, body={
            "startDate": mulai, "endDate": akhir, "dimensions": ["page"], "rowLimit": 1000}).execute().get("rows", [])
        klik = sum(r["clicks"] for r in rows); imp = sum(r["impressions"] for r in rows)
        print(f"\n  ── {label} ── klik {klik} | impresi {imp} | CTR {round(klik/imp*100, 2) if imp else 0}%")
        print("     halaman teratas:")
        for r in sorted(rows, key=lambda x: -x["impressions"])[:8]:
            print(f"       imp {r['impressions']:>5} | klik {r['clicks']:>3} | pos {round(r['position'],1):>5} | {r['keys'][0].replace(SITE, '/')[:52]}")
        q = gsc.searchanalytics().query(siteUrl=SITE, body={
            "startDate": mulai, "endDate": akhir, "dimensions": ["query"], "rowLimit": 1000}).execute().get("rows", [])
        print("     query teratas:")
        for r in sorted(q, key=lambda x: -x["impressions"])[:10]:
            print(f"       imp {r['impressions']:>5} | klik {r['clicks']:>3} | pos {round(r['position'],1):>5} | {r['keys'][0][:54]}")
    except Exception as e:
        print(f"  {label}: gagal — {str(e)[:120]}")

print("\n=== GA4 properti ===")
adm = build("analyticsadmin", "v1beta",
            credentials=service_account.Credentials.from_service_account_file(
                KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)
prop = None
for a in adm.accountSummaries().list().execute().get("accountSummaries", []):
    for p in a.get("propertySummaries", []):
        if "skin" in (p.get("displayName") or "").lower():
            prop = p["property"]
            print(f"   {p['property']} → {p.get('displayName')} (akun {a.get('displayName')})")

if prop:
    ga = build("analyticsdata", "v1beta",
               credentials=service_account.Credentials.from_service_account_file(
                   KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)

    def rep(dims, mets, mulai, akhir, limit=12, urut=None, kanal=None):
        b = {"dateRanges": [{"startDate": mulai, "endDate": akhir}],
             "dimensions": [{"name": d} for d in dims], "metrics": [{"name": m} for m in mets], "limit": limit}
        if urut:
            b["orderBys"] = [{"metric": {"metricName": urut}, "desc": True}]
        if kanal:
            b["dimensionFilter"] = {"filter": {"fieldName": "sessionDefaultChannelGroup",
                                               "stringFilter": {"value": kanal, "matchType": "EXACT"}}}
        return ga.properties().runReport(property=prop, body=b).execute().get("rows", [])

    for label, mulai, akhir in (("28 hari", "2026-08-29", "2026-09-25"), ("90 hari", "2026-06-28", "2026-09-25")):
        print(f"\n  ── GA4 {label} ──")
        r = rep([], ["sessions", "totalUsers", "screenPageViews", "keyEvents", "averageSessionDuration",
                     "engagementRate"], mulai, akhir, 1)
        if r:
            v = [x["value"] for x in r[0]["metricValues"]]
            print(f"     sesi {v[0]} | pengguna {v[1]} | halaman {v[2]} | kejadian kunci {v[3]} | "
                  f"durasi {round(float(v[4]))}s | engagement {round(float(v[5])*100)}%")
        print("     kanal:")
        for row in rep(["sessionDefaultChannelGroup"], ["sessions", "keyEvents"], mulai, akhir, 8, "sessions"):
            print(f"       {row['dimensionValues'][0]['value'][:20]:<22} sesi {row['metricValues'][0]['value']:>4}")
        print("     halaman pendaratan:")
        for row in rep(["landingPagePlusQueryString"], ["sessions", "userEngagementDuration"], mulai, akhir, 8, "sessions"):
            d = row["dimensionValues"][0]["value"]; v = [x["value"] for x in row["metricValues"]]
            print(f"       sesi {v[0]:>4} | {round(float(v[1])/max(int(v[0]),1)):>4}s | {d[:54]}")

    print("\n  ── kota (90 hari) ──")
    for row in rep(["city"], ["sessions"], "2026-06-28", "2026-09-25", 10, "sessions"):
        print(f"     {row['dimensionValues'][0]['value'][:26]:<28} {row['metricValues'][0]['value']}")
    print("\n  ── kejadian (90 hari) ──")
    for row in rep(["eventName"], ["eventCount"], "2026-06-28", "2026-09-25", 20, "eventCount"):
        print(f"     {row['dimensionValues'][0]['value'][:28]:<30} {row['metricValues'][0]['value']}")

print("\n=== kondisi situs ===")
for u in ("https://theskincodeclinic.com/", "https://www.theskincodeclinic.com/", "https://www.theskincodeclinic.com/robots.txt", "https://www.theskincodeclinic.com/sitemap_index.xml"):
    t0 = time.time()
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60)
        isi = r.read()
        print(f"   {r.status} | {round(time.time()-t0,2)}s | {len(isi)//1024:>4} KB | cf={r.headers.get('cf-cache-status')} | {u}")
    except urllib.error.HTTPError as e:
        print(f"   {e.code} | {round(time.time()-t0,2)}s | lokasi={e.headers.get('Location')} | {u}")
    except Exception as e:
        print(f"   ERR {str(e)[:40]} | {u}")
