#!/usr/bin/env python3
"""Post konten Facebook DAS Bengkel Indonesia via Repliz
Format: image (1080x1350) + caption 2-4 paragraf + link artikel dasindonesia.com
Jam: 17:00 WIB
Konten WAJIB UNIK — tidak boleh berulang dengan yang sudah pernah diposting.
"""

import urllib.request, json, base64, os, sys
from datetime import datetime, timezone, timedelta

import base64

from repliz_client import upload_image_to_server, HEADERS, BASE
WIB = timezone(timedelta(hours=7))

FB_DAS_ID = '6a3b41e1c5ff4ce3a327543e'

# === HISTORY LOG — catat semua postingan biar gak redundan ===
LOG_FILE = os.path.join(os.path.dirname(__file__), 'post_das_fb_history.json')

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

def save_history(history):
    with open(LOG_FILE, 'w') as f:
        json.dump(history, f, indent=2)

def is_duplicate(history, caption_short, article_url):
    """Cek apakah konten ini udah pernah diposting"""
    for p in history['posts']:
        if p.get('article_url') == article_url:
            return True
        # Cek kata kunci dari judul artikel
        words = set(caption_short.lower().split()[:10])
        p_words = set(p.get('short_desc', '').lower().split()[:10])
        common = words & p_words
        if len(common) >= 5:
            return True
    return False

def schedule_post(img_path, caption, article_url, jam_wib='17:00'):
    """Schedule posting FB DAS"""
    history = load_history()
    
    # Cek duplikasi
    short_desc = caption.split('\n\n')[0][:100] if '\n\n' in caption else caption[:100]
    if is_duplicate(history, short_desc, article_url):
        print(f'❌ DUPLICATE DETECTED! Konten ini udah pernah diposting: {article_url}')
        return None
    
    # Baca & encode gambar
    img_url = upload_image_to_server(img_path)
    # FIX 21/08: no base64 — image via server OpenClaw
    
    # Waktu posting
    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')
    
    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', '?')
            
            # Catat ke history
            history['posts'].append({
                'date': schedule_at.strftime('%Y-%m-%d'),
                'time': jam_wib,
                'article_url': article_url,
                'short_desc': short_desc,
                'schedule_id': sid,
            })
            save_history(history)
            
            print(f'✅ FB DAS — {schedule_at.strftime("%d %b %Y %H:%M")} WIB')
            print(f'   Schedule ID: {sid}')
            print(f'   Artikel: {article_url}')
            return sid
    except urllib.error.HTTPError as e:
        err = e.read().decode()
        print(f'❌ ERROR {e.code}: {err[:300]}')
        return None


# ===== MAIN =====
if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('Usage: python3 post_das_fb.py <image_path> <article_url>')
        print('Caption akan diinput manual atau dari stdin')
        sys.exit(1)
    
    img_path = sys.argv[1]
    article_url = sys.argv[2]
    
    # Baca caption dari pipe atau arg
    if not sys.stdin.isatty():
        caption = sys.stdin.read().strip()
    else:
        print('Masukkan caption (akhiri dengan Ctrl+D):')
        caption = sys.stdin.read().strip()
    
    if not caption:
        print('❌ Caption kosong!')
        sys.exit(1)
    
    schedule_post(img_path, caption, article_url)

