#!/usr/bin/env python3
"""Schedule FB DAS Bengkel Indonesia — 8 Sep 2026
Cron jalan ~17:00-17:05 WIB → slot 17:00 sudah lewat → pakai slot KOSONG berikutnya: 20:00 WIB hari ini
(preseden schedule_das_fb_20260901..07.py + universal slot rule).
Artikel: https://dasindonesia.com/kapan-mobil-perlu-engine-overhaul/
- LIVE (HTTP 200, diverifikasi 8 Sep 2026 via WP REST + curl)
- BELUM pernah dipakai di akun FB DAS: 0 hit di riwayat live Repliz DAS FB (SEMUA status, scan API),
  repliz_audit_dump.json, maupun log lokal lainnya. (Entri history 15/28 Jul = era pra-platform, jadwal
  sudah 404/terhapus; varian penyebab-mesin-mobil-overheat-dan-cara-mencegahnya tayang 29 Agu = slug BEDA,
  jangan dipakai → dipilih kapan-mobil-perlu-engine-overhaul agar tidak duplikat tematik dgn 29 Agu.)
Format: image 1080x1350 (bg #1a1a2e, teks putih, aksen #f97316) + caption 3 paragraf + link + pancingan diskusi (opini)
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_20260908.png')
ARTICLE_URL = "https://dasindonesia.com/kapan-mobil-perlu-engine-overhaul/"

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

CAPTION = """Mobil mulai menunjukkan tanda yang tidak biasa — asap knalpot berubah warna, suara mesin makin kasar, atau oli cepat habis padahal tidak ada kebocoran? Jangan buru-buru menganggapnya angin lalu. Bisa jadi ini cara mesin memberi sinyal bahwa sudah waktunya pemeriksaan lebih dalam.

Tanda yang perlu diwaspadai antara lain asap putih pekat yang terus keluar setelah mesin panas, asap kebiruan yang menandakan oli ikut terbakar, hingga bunyi ketukan dari dalam mesin. Kalau dibiarkan, kerusakan kecil bisa menjalar ke komponen lain dan berujung penanganan yang jauh lebih besar. Penjelasan lengkap soal kapan mobil sebaiknya menjalani engine overhaul sudah saya rangkum di artikel berikut: https://dasindonesia.com/kapan-mobil-perlu-engine-overhaul/

Bold statement: banyak pemilik mobil memilih "lihat nanti saja" saat tanda-tanda ini muncul, padahal justru di titik inilah keputusan cepat sangat menentukan. Setuju atau tidak? Pernah mengalami salah satu tandanya? Yuk cerita di kolom komentar."""


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_on(day):
    """Cek jadwal pending/draft DAS FB pada tanggal tertentu — 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(day):
                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': ARTICLE_URL in cap,
        'ada ajakan diskusi': any(w in cap.lower() for w in ['komentar', 'ceritakan', 'pendapat', 'menurut', 'bagaimana', 'yuk', 'setuju', 'bold statement']),
        'tanpa kata harga/biaya': not any(w in cap.lower() for w in banned),
        'paragraf >= 2': len(cap.split('\n\n')) >= 2,
        'paragraf <= 4': len(cap.split('\n\n')) <= 4,
    }
    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_on(TGL)
    print(f"  DAS FB pending {TGL}: {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 (history era sekarang; entri Jul = jadwal 404/terhapus, bukan tayang akun ini)
    print(f"  Catatan: artikel {ARTICLE_URL} pernah tercatat di history 15/28 Jul era pra-platform "
          f"(jadwal sudah 404), 0 hit di riwayat akun FB DAS semua status.")
    print(f"✅ Artikel layak 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: {TGL} {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_on(TGL)
            print(f"   Verifikasi pending DAS FB {TGL}: {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': TGL,
                '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()
