#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""TSC: tarik permintaan nyata warga (GSC + GA4) untuk menyusun topik konten.

Rentang: 90 hari terakhir (2026-07-16 s/d 2026-10-13) + 28 hari terakhir.
Hasil disimpan ke drafts/tsc_permintaan_20261014.md
"""
import os

from google.oauth2 import service_account
from googleapiclient.discovery import build

KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
SITE = "https://www.theskincodeclinic.com/"
HARI90 = ("2026-07-16", "2026-10-13")
HARI28 = ("2026-09-16", "2026-10-13")
KELUAR = "/home/mantapman/.hermes/profiles/atun/workspace/drafts/tsc_permintaan_20261014.md"

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)

baris = ["# Permintaan nyata warga sekitar — The Skin Code Clinic (diperbarui 14 Okt 2026)", "",
         f"Rentang: {HARI90[0]} s/d {HARI90[1]} (90 hari) dan {HARI28[0]} s/d {HARI28[1]} (28 hari).", ""]


def q(dims, mulai, akhir, limit=200):
    return gsc.searchanalytics().query(siteUrl=SITE, body={
        "startDate": mulai, "endDate": akhir, "dimensions": dims, "rowLimit": limit}).execute().get("rows", [])


for label, (a, b) in (("90 hari", HARI90), ("28 hari", HARI28)):
    rows = q(["query"], a, b)
    klik = sum(r["clicks"] for r in rows)
    imp = sum(r["impressions"] for r in rows)
    baris += [f"## Kueri {label} — {len(rows)} kueri | klik {klik} | tayangan {imp}", "",
              "```", f"{'kueri':<52}{'tayang':>8}{'klik':>6}{'pos':>7}"]
    for r in sorted(rows, key=lambda x: -x["impressions"])[:30]:
        baris.append(f"{r['keys'][0][:50]:<52}{r['impressions']:>8}{r['clicks']:>6}{round(r['position'],1):>7}")
    baris += ["```", ""]

    hr = q(["page"], a, b)
    baris += [f"## Halaman {label} (15 teratas menurut tayangan)", "", "```"]
    for r in sorted(hr, key=lambda x: -x["impressions"])[:15]:
        baris.append(f"{r['impressions']:>7} tayang | {r['clicks']:>4} klik | pos {round(r['position'],1):>5} | "
                     f"{r['keys'][0].replace(SITE, '/')[:56]}")
    baris += ["```", ""]

# GA4
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 acc in adm.accountSummaries().list().execute().get("accountSummaries", []):
    for p in acc.get("propertySummaries", []):
        if "skin" in (p.get("displayName") or "").lower():
            prop = p["property"]
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=15, urut=None):
        body = {"dateRanges": [{"startDate": mulai, "endDate": akhir}],
                "dimensions": [{"name": d} for d in dims], "metrics": [{"name": m} for m in mets], "limit": limit}
        if urut:
            body["orderBys"] = [{"metric": {"metricName": urut}, "desc": True}]
        return ga.properties().runReport(property=prop, body=body).execute().get("rows", [])

    baris += ["## GA4 — 90 hari", ""]
    r = rep([], ["sessions", "totalUsers", "keyEvents", "engagementRate"], HARI90[0], HARI90[1], 1)
    if r:
        v = [x["value"] for x in r[0]["metricValues"]]
        baris += [f"sesi {v[0]} | pengguna {v[1]} | kejadian kunci {v[2]} | engagement {round(float(v[3]) * 100)}%", ""]
    baris += ["Halaman pendaratan teratas:", "```"]
    for row in rep(["landingPagePlusQueryString"], ["sessions", "keyEvents"], HARI90[0], HARI90[1], 15, "sessions"):
        v = [x["value"] for x in row["metricValues"]]
        baris.append(f"{v[0]:>5} sesi | {v[1]:>3} kunci | {row['dimensionValues'][0]['value'][:56]}")
    baris += ["```", "", "Kota pengunjung:", "```"]
    for row in rep(["city"], ["sessions"], HARI90[0], HARI90[1], 12, "sessions"):
        baris.append(f"{row['metricValues'][0]['value']:>5} sesi | {row['dimensionValues'][0]['value']}")
    baris += ["```", "", "Kanal:", "```"]
    for row in rep(["sessionDefaultChannelGroup"], ["sessions", "keyEvents"], HARI90[0], HARI90[1], 10, "sessions"):
        v = [x["value"] for x in row["metricValues"]]
        baris.append(f"{v[0]:>5} sesi | {row['dimensionValues'][0]['value']}")
    baris += ["```", ""]

with open(KELUAR, "w", encoding="utf-8") as f:
    f.write("\n".join(baris) + "\n")
print("tersimpan:", KELUAR)
print("\n".join(baris[:60]))
