#!/usr/bin/env python3
"""PENTING: pisahkan data GA4 berdasarkan hostName — memastikan halaman pendaratan itu milik
theskincodeclinic.com atau surabaya-skincentre.com, dan cek status URL di kedua situs."""
import os, time, urllib.request, urllib.error
from google.oauth2 import service_account
from googleapiclient.discovery import build

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"}
ga = build("analyticsdata", "v1beta",
           credentials=service_account.Credentials.from_service_account_file(
               KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)

print("=== 1. GA4 properti 490140645 (skincodeclinic.com) — per HOSTNAME (90 hari) ===")
r = ga.properties().runReport(property="properties/490140645", body={
    "dateRanges": [{"startDate": "2026-06-28", "endDate": "2026-09-25"}],
    "dimensions": [{"name": "hostName"}],
    "metrics": [{"name": "sessions"}, {"name": "totalUsers"}],
    "limit": 20, "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}]}).execute()
for row in r.get("rows", []):
    print(f"   {row['dimensionValues'][0]['value'][:40]:<42} sesi {row['metricValues'][0]['value']:>5} | "
          f"pengguna {row['metricValues'][1]['value']:>5}")

print("\n=== 2. halaman pendaratan per hostname (10 teratas) ===")
r = ga.properties().runReport(property="properties/490140645", body={
    "dateRanges": [{"startDate": "2026-06-28", "endDate": "2026-09-25"}],
    "dimensions": [{"name": "hostName"}, {"name": "landingPagePlusQueryString"}],
    "metrics": [{"name": "sessions"}], "limit": 25,
    "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}]}).execute()
for row in r.get("rows", []):
    print(f"   sesi {row['metricValues'][0]['value']:>5} | {row['dimensionValues'][0]['value'][:30]:<32} {row['dimensionValues'][1]['value'][:56]}")

print("\n=== 3. properti GA4 milik surabaya-skincentre.com (513751849) — hostname ===")
try:
    r = ga.properties().runReport(property="properties/513751849", body={
        "dateRanges": [{"startDate": "2026-06-28", "endDate": "2026-09-25"}],
        "dimensions": [{"name": "hostName"}], "metrics": [{"name": "sessions"}],
        "limit": 10, "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}]}).execute()
    for row in r.get("rows", []):
        print(f"   {row['dimensionValues'][0]['value'][:40]:<42} sesi {row['metricValues'][0]['value']}")
except Exception as e:
    print("   gagal:", str(e)[:100])

print("\n=== 4. status URL di kedua situs ===")
for basis in ("https://www.theskincodeclinic.com", "https://www.surabaya-skincentre.com"):
    print(f"\n   {basis}")
    for u in ("/", "/profil/", "/jadwal-dokter/", "/dermatologi-anak/", "/jadwal-dokter", "/profil"):
        try:
            t0 = time.time()
            rr = urllib.request.urlopen(urllib.request.Request(basis + u, headers=UA), timeout=60)
            print(f"      {rr.status} | {u:<22} {round(time.time()-t0,2)}s")
        except urllib.error.HTTPError as e:
            print(f"      {e.code} | {u}")
        except Exception as e:
            print(f"      ERR | {u} ({str(e)[:30]})")
