#!/usr/bin/env python3
"""Schedule FB DAS Bengkel Indonesia — 1 Sep 2026 (slot 20:00 WIB, krn 17:00 sudah lewat)
Artikel: https://dasindonesia.com/bengkel-resmi-vs-spesialis-vs-umum/ (200 OK, belum pernah dipakai)
Format: image 1080x1350 + caption 3 paragraf + link artikel + pancingan diskusi (tone opini)
"""
import json, os, sys, urllib.request
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_20260901.png')
ARTICLE_URL = "https://dasindonesia.com/bengkel-resmi-vs-spesialis-vs-umum/"
JAM_WIB = "20:00"  # 17:00 sudah lewat saat cron jalan (17:11 WIB) — pakai slot 20:00 WIB hari ini (preseden history)

CAPTION = """Masih banyak yang bingung: mobil harus diservis di bengkel resmi, bengkel spesialis, atau bengkel umum? Jawabannya tidak hitam-putih — semua punya tempatnya masing-masing.

Bengkel resmi unggul di standar pabrikan dan garansi, tapi harganya paling mahal dan antreannya panjang. Bengkel umum murah dan fleksibel, tapi kualitasnya tergantung teknisi. Nah, bengkel spesialis — seperti DAS Indonesia — fokus di satu bidang: overhaul mesin, transmisi matic, dan perawatan mobil premium. Keahliannya lebih dalam untuk masalah yang rumit.

Kuncinya sesuaikan dengan kondisi mobil Anda: masih garansi? Resmi. Masalahnya kompleks? Spesialis. Cuma ganti oli atau rem? Bengkel umum terpercaya sudah cukup. Bahkan banyak pemilik cerdas mengombinasikan ketiganya biar hemat tapi tetap aman.

Penjelasan lengkap kelebihan, kekurangan, dan kapan harus ke bengkel mana sudah kami rangkum di sini: https://dasindonesia.com/bengkel-resmi-vs-spesialis-vs-umum/

Kontroversial: servis di bengkel spesialis itu bukan mahal, tapi justru lebih murah daripada salah diagnosis di bengkel umum. Anda tim mana?"""


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 main():
    history = load_history()

    # 1. Cek duplikat
    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}")

    # 2. Upload image ke server OpenClaw
    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)

    # 3. Schedule jam WIB
    now = datetime.now(WIB)
    h, m = JAM_WIB.split(':')
    schedule_at = now.replace(hour=int(h), minute=int(m), second=0, microsecond=0)
    schedule_iso = schedule_at.strftime('%Y-%m-%dT%H:%M:%S.000Z')
    print(f"   Schedule: {schedule_at.strftime('%d %b %Y %H:%M')} WIB ({schedule_iso})")

    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,
    }

    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) 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. Catat history
            history['posts'].append({
                'date': schedule_at.strftime('%Y-%m-%d'),
                '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()
