#!/usr/bin/env python3
"""Schedule FB DAS Bengkel Indonesia — 4 Sep 2026
Cron jalan ~17:00 WIB → slot 17:00 sudah lewat → pakai slot KOSONG berikutnya: 20:00 WIB hari ini
(preseden schedule_das_fb_20260901/02/03.py + universal slot rule).
Artikel: https://dasindonesia.com/pentingnya-overhaul-mesin-kerugian-bila-terlambat/
- LIVE (HTTP 200) — batch premium 19 Agu (sebelumnya: standar-kerja dipakai 3 Sep)
- BELUM pernah dipakai: tidak ada di post_das_fb_history.json, riwayat Repliz DAS FB/IG (dump), maupun Threads log
Format: image 1080x1350 (bg #1a1a2e, teks putih, aksen #f97316) + caption 4 paragraf + link + pancingan diskusi (netral)
Aturan DAS: NO HARGA/biaya/murah/mahal/hemat; positioning Amanah-Profesional-Melebihi Harapan; wajib pancingan diskusi; 0 mention internal.
"""
import json, os, sys, subprocess, time, urllib.request, urllib.error
from datetime import datetime, timezone, timedelta

from repliz_client import upload_image_to_server, HEADERS, BASE, ACC

WIB = timezone(timedelta(hours=7))
FB_DAS_ID = ACC.DAS_FB  # 6a3b41e1c5ff4ce3a327543e
LOG_FILE = os.path.join(os.path.dirname(__file__), 'post_das_fb_history.json')
IMG_PATH = os.path.join(os.path.dirname(__file__), 'das_fb_20260904.png')
ARTICLE_URL = "https://dasindonesia.com/pentingnya-overhaul-mesin-kerugian-bila-terlambat/"

# 17:00 WIB sudah lewat (cron jalan ~17:00-17:01 WIB) → slot kosong berikutnya hari ini = 20:00 WIB = 13:00 UTC
JAM_WIB = "20:00"
schedule_iso = "2026-09-04T13:00:00.000Z"

CAPTION = """Pernah lihat asap putih atau kebiruan mengepul dari knalpot, lalu memilih "abaikan dulu, yang penting masih jalan"? Hati-hati, itu salah satu sinyal awal mesin mulai aus — dan kalau dibiarkan, yang tadinya sekadar ring aus bisa merembet ke dinding silinder sampai butuh penanganan jauh lebih besar.

Saya sering menemui pemilik mobil yang baru sadar pentingnya overhaul justru saat masalahnya sudah di ambang fatal. Padahal tanda-tandanya sebenarnya sudah terlihat dari jauh: oli cepat habis tanpa kebocoran yang jelas, tenaga terasa berat, suara knocking mulai muncul, sampai konsumsi BBM yang membengkak tiba-tiba. Mesin yang sehat itu kerjanya senyap; begitu mulai "protes", itu alarm yang tidak boleh dianggap remeh.

Overhaul memang terdengar menakutkan, tapi menundanya justru lebih berisiko — apalagi kalau sampai mogok di tengah perjalanan jauh atau mudik. Mengenal gejalanya sejak dini dan memeriksakan mesin sebelum parah itu bentuk sayang yang paling masuk akal buat kendaraan kesayangan Anda. Di artikel ini saya rangkum apa saja kerugian yang mengintai kalau overhaul ditunda dan tanda-tanda yang wajib Anda waspadai: https://dasindonesia.com/pentingnya-overhaul-mesin-kerugian-bila-terlambat/

Mobil Anda pernah menunjukkan gejala-gejala ini? Ceritakan pengalamanmu di kolom komentar, yuk!"""


def load_history():
    if os.path.exists(LOG_FILE):
        with open(LOG_FILE) as f:
            return json.load(f)
    return {'posts': []}


def is_duplicate(history, article_url):
    for p in history['posts']:
        if p.get('article_url', '').rstrip('/') == article_url.rstrip('/'):
            return True
    return False


def pending_das_fb_today():
    """Cek jadwal pending/draft DAS FB hari ini (4 Sep 2026) — hindari double-book."""
    hits = []
    page = 1
    while True:
        try:
            req = urllib.request.Request(f'{BASE}/public/schedule?page={page}&limit=100',
                                         headers=HEADERS, method='GET')
            with urllib.request.urlopen(req, timeout=30) as r:
                data = json.loads(r.read())
        except Exception as e:
            print(f"  ⚠️ Gagal list schedules page {page}: {e}")
            break
        docs = data.get('docs', [])
        for d in docs:
            if d.get('accountId') != FB_DAS_ID:
                continue
            st = d.get('status')
            sched = d.get('scheduleAt', '')
            if st in ('pending', 'draft') and sched.startswith('2026-09-04'):
                hits.append((sched, d.get('_id')))
        if page >= data.get('totalPages', 1):
            break
        page += 1
    return hits


def verify_caption(cap):
    """Verifikasi wajib: 0 mention, ada link, ada ajakan diskusi, tanpa kata harga/biaya."""
    import re
    banned = ['harga', 'biaya', 'murah', 'mahal', 'hemat', 'juta', 'rupiah']
    checks = {
        '0 mention @': not re.search(r'@\w+', cap),
        'ada link dasindonesia': 'https://dasindonesia.com/pentingnya-overhaul-mesin-kerugian-bila-terlambat/' in cap,
        'ada ajakan diskusi': any(w in cap.lower() for w in ['komentar', 'ceritakan', 'pendapat', 'menurut', 'bagaimana', 'yuk']),
        'tanpa kata harga/biaya': not any(w in cap.lower() for w in banned),
        'paragraf >= 2': len(cap.split('\n\n')) >= 2,
    }
    for k, v in checks.items():
        print(f"   [{'✅' if v else '❌'}] {k}")
    return all(checks.values())


def main():
    history = load_history()

    # 0. Slot: tidak boleh ada pending DAS FB hari ini
    pend = pending_das_fb_today()
    print(f"  DAS FB pending 4 Sep 2026: {pend if pend else 'TIDAK ADA'}")
    if pend:
        print("❌ Sudah ada jadwal DAS FB hari ini — batal, jangan double-book")
        sys.exit(1)

    # 1. Cek duplikat artikel
    if is_duplicate(history, ARTICLE_URL):
        print(f"❌ DUPLICATE: {ARTICLE_URL} sudah pernah diposting")
        sys.exit(1)
    print(f"✅ Artikel belum pernah dipakai: {ARTICLE_URL}")

    # 1b. Verifikasi caption
    if not verify_caption(CAPTION):
        print("❌ Caption gagal verifikasi — batal")
        sys.exit(1)

    # 2. Upload image ke server OpenClaw (konversi otomatis ke JPEG di openclaw-img/)
    img_url = upload_image_to_server(IMG_PATH)
    print(f"   Image URL: {img_url}")
    if not img_url:
        print("❌ Upload image gagal — batal")
        sys.exit(1)

    # 2b. Verifikasi URL via jalur INTERNET (ingress funnel), bukan tailnet lokal
    ok_ingress = False
    for ip in ("103.84.155.153", "103.84.155.217"):
        code = subprocess.run(
            ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "25",
             "--resolve", f"mantapserver.tail3947bb.ts.net:443:{ip}", img_url],
            capture_output=True, text=True).stdout
        print(f"   Ingress {ip}: HTTP {code}")
        if code == "200":
            ok_ingress = True
    code_local = subprocess.run(
        ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "15", img_url],
        capture_output=True, text=True).stdout
    print(f"   Local fetch: HTTP {code_local}")
    if not ok_ingress:
        print("❌ URL gambar tidak bisa diakses via ingress funnel — batal (Repliz ambil dari internet)")
        sys.exit(1)

    # 3. Payload — scheduleAt WAJIB UTC (20:00 WIB = 13:00 UTC)
    payload = {
        'title': '',
        'description': CAPTION,
        'topic': 'Otomotif',
        'type': 'image',
        'medias': [{'url': img_url, 'type': 'image'}],
        'meta': {'title': '', 'description': '', 'url': ''},
        'additionalInfo': {
            'isAiGenerated': False, 'isDraft': False,
            'collaborators': [], 'mentions': [],
            'music': {'id': '', 'artist': '', 'name': '', 'thumbnail': ''},
            'products': [], 'tags': []
        },
        'replies': [],
        'accountId': FB_DAS_ID,
        'scheduleAt': schedule_iso,
    }
    print(f"   Schedule: 4 Sep 2026 {JAM_WIB} WIB ({schedule_iso})")

    body = json.dumps(payload).encode()
    req = urllib.request.Request(f'{BASE}/public/schedule', data=body, headers=HEADERS, method='POST')
    try:
        with urllib.request.urlopen(req, timeout=40) as r:
            result = json.loads(r.read())
            sid = result.get('scheduleId') or result.get('_id') or result.get('id') or '?'
            print(f"✅ SCHEDULED — Schedule ID: {sid}")

            # 4. Verifikasi dari API: cari pending account tsb di scheduleAt tsb
            time.sleep(3)
            ver = pending_das_fb_today()
            print(f"   Verifikasi pending DAS FB 4 Sep: {ver}")
            if not ver:
                print("❌ Tidak ketemu jadwal pending di API — cek manual, jangan catat history dulu")
                sys.exit(1)
            sid_verified = ver[0][1]
            if sid == '?':
                sid = sid_verified

            # 5. Catat history
            history['posts'].append({
                'date': '2026-09-04',
                'time': JAM_WIB,
                'platform': 'facebook',
                'article_url': ARTICLE_URL,
                'short_desc': CAPTION.split('\n\n')[0][:100],
                'schedule_id': sid,
                'image_source': 'openclaw-img',
            })
            with open(LOG_FILE, 'w') as f:
                json.dump(history, f, indent=2)
            print(f"   History dicatat: {LOG_FILE}")
            print(f"   Total posts: {len(history['posts'])}")
            return sid
    except urllib.error.HTTPError as e:
        err = e.read().decode()
        print(f"❌ ERROR {e.code}: {err[:500]}")
        sys.exit(1)


if __name__ == '__main__':
    main()
