#!/usr/bin/env python3
"""Schedule FB DAS Bengkel Indonesia — 7 Sep 2026
Cron jalan ~17:05 WIB → slot 17:00 sudah lewat → pakai slot KOSONG berikutnya: 20:00 WIB hari ini
(preseden schedule_das_fb_20260901..06.py + universal slot rule).
Artikel: https://dasindonesia.com/perawatan-flushing-ac-mobil-agar-tetap-dingin-das-indonesia-surabaya/
- LIVE (HTTP 200, diverifikasi 7 Sep 2026 via WP REST + curl)
- BELUM pernah dipakai: 0 hit di post_das_fb_history.json, riwayat live Repliz DAS FB/IG (SEMUA status),
  repliz_audit_dump.json, maupun log lokal (Threads/crosspost/short)
Format: image 1080x1350 (bg #1a1a2e, teks putih, aksen #f97316) + caption 3 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_20260907.png')
ARTICLE_URL = "https://dasindonesia.com/perawatan-flushing-ac-mobil-agar-tetap-dingin-das-indonesia-surabaya/"

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

CAPTION = """AC mobil mulai terasa kurang dingin padahal freon baru saja diisi? Atau muncul bau tak sedap setiap kali dinyalakan? Jangan buru-buru menyalahkan cuaca — bisa jadi saluran AC di dalamnya sudah kotor dan butuh dibersihkan menyeluruh.

Flushing AC adalah proses membersihkan seluruh saluran sistem AC dari kotoran dan kontaminasi, lengkap dengan penggantian dryer filter dan oli kompresor sebelum freon diisi ulang sesuai spesifikasi pabrikan. Perawatan ini penting dilakukan saat AC terasa kurang dingin, muncul bau tak sedap, atau sudah lama tidak pernah diservis menyeluruh. Ulasan lengkap tanda-tanda dan prosesnya sudah saya rangkum di artikel berikut: https://dasindonesia.com/perawatan-flushing-ac-mobil-agar-tetap-dingin-das-indonesia-surabaya/

Kapan terakhir kali AC mobil Anda diservis menyeluruh? Kalau selama ini cuma sekadar isi freon, mungkin ini saatnya lebih teliti. Yuk cerita pengalamanmu 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
    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: {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()
