#!/usr/bin/env python3
"""Cek GSC + GA4 yasmanatura.co.id: tren, brand vs non-brand, query, halaman, channel."""
import os, json
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/webmasters.readonly",
            "https://www.googleapis.com/auth/analytics.readonly"])
gsc = build("webmasters", "v3", credentials=creds, cache_discovery=False)
data = build("analyticsdata", "v1beta", credentials=creds, cache_discovery=False)
S = "https://yasmanatura.co.id/"
GA4 = "properties/491116493"
e = date.today() - timedelta(days=2)
S28 = (e - timedelta(days=27)).isoformat()
S90 = (e - timedelta(days=89)).isoformat()
END = e.isoformat()


def q(body):
    return gsc.searchanalytics().query(siteUrl=S, body=body).execute().get("rows", [])


print("=== TREN GSC ===")
for label, a, b in (("28d terakhir", S28, END),
                    ("28d sebelumnya", (e - timedelta(days=55)).isoformat(), (e - timedelta(days=28)).isoformat()),
                    ("90d", S90, END)):
    r = q({"startDate": a, "endDate": b, "dimensions": [], "rowLimit": 1})
    if r:
        x = r[0]
        print(f"  {label:<15} {a}→{b}: {int(x['clicks'])} klik | {int(x['impressions'])} impresi | "
              f"CTR {x['ctr']*100:.2f}% | pos {x['position']:.1f}")

print("\n=== per minggu (10 minggu) ===")
for i in range(10):
    b = e - timedelta(days=7 * i); a = b - timedelta(days=6)
    r = q({"startDate": a.isoformat(), "endDate": b.isoformat(), "dimensions": [], "rowLimit": 1})
    if r:
        x = r[0]
        print(f"  {a} → {b}: {int(x['clicks']):>4} klik | {int(x['impressions']):>6} impresi | pos {x['position']:>5.1f}")

rows = q({"startDate": S90, "endDate": END, "dimensions": ["query"], "rowLimit": 5000})
BRAND = ("yasma", "yasmanatura", "yasma natura")
brand = [r for r in rows if any(x in r["keys"][0].lower() for x in BRAND)]
non = [r for r in rows if r not in brand]


def agg(rs):
    c = sum(r["clicks"] for r in rs); i = sum(r["impressions"] for r in rs)
    p = sum(r["position"] * r["impressions"] for r in rs) / i if i else 0
    return len(rs), int(i), int(c), p


print(f"\n=== 90 hari: {len(rows)} query ===")
for nama, grp in (("BRAND", brand), ("NON-BRAND", non)):
    n, i, c, p = agg(grp)
    print(f"  {nama:<10} {n:>4} query | {i:>6} impresi | {c:>4} klik | CTR {c/i*100 if i else 0:>5.2f}% | pos {p:>5.1f}")

print("\n=== 15 query klik terbanyak ===")
for r in sorted(rows, key=lambda x: -x["clicks"])[:15]:
    print(f"  {int(r['clicks']):>4} klik | {int(r['impressions']):>5} imp | CTR {r['ctr']*100:>5.1f}% | pos {r['position']:>5.1f} | {r['keys'][0]}")

print("\n=== halaman paling banyak klik ===")
for r in q({"startDate": S90, "endDate": END, "dimensions": ["page"], "rowLimit": 12}):
    print(f"  {int(r['clicks']):>4} klik | {int(r['impressions']):>5} imp | CTR {r['ctr']*100:>5.1f}% | pos {r['position']:>5.1f} | {r['keys'][0].replace(S,'')[:58]}")

print("\n=== peluang: impresi >=20, klik 0, posisi <=20 (90d) ===")
pel = [r for r in rows if r["clicks"] == 0 and r["impressions"] >= 20 and r["position"] <= 20]
for r in sorted(pel, key=lambda x: -x["impressions"])[:12]:
    print(f"  {int(r['impressions']):>5} imp | pos {r['position']:>5.1f} | {r['keys'][0][:60]}")

print("\n=== GA4 28 hari ===")
try:
    for x in data.properties().runReport(property=GA4, body={
            "dateRanges": [{"startDate": S28, "endDate": END}],
            "metrics": [{"name": m} for m in ("sessions", "totalUsers", "screenPageViews", "engagementRate")]}).execute().get("rows", []):
        v = [m["value"] for m in x["metricValues"]]
        print(f"  sesi {v[0]} | user {v[1]} | pageview {v[2]} | engagement {float(v[3])*100:.1f}%")
    print("  --- channel ---")
    for x in data.properties().runReport(property=GA4, body={
            "dateRanges": [{"startDate": S28, "endDate": END}],
            "dimensions": [{"name": "sessionDefaultChannelGroup"}], "metrics": [{"name": "sessions"}],
            "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}]}).execute().get("rows", []):
        print(f"    {x['dimensionValues'][0]['value']:<22} {x['metricValues'][0]['value']}")
    print("  --- halaman masuk teratas ---")
    for x in data.properties().runReport(property=GA4, body={
            "dateRanges": [{"startDate": S28, "endDate": END}],
            "dimensions": [{"name": "landingPagePlusQueryString"}],
            "metrics": [{"name": "sessions"}],
            "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}], "limit": 8}).execute().get("rows", []):
        print(f"    {x['metricValues'][0]['value']:>4} sesi | {x['dimensionValues'][0]['value'][:56]}")
except Exception as ex:
    print("  GA4 error:", str(ex)[:200])
