#!/usr/bin/env python3
"""Schedule DAS FB post for today 17:00 WIB — engine overhaul article"""
import urllib.request, json, base64, os, sys
from datetime import datetime, timezone, timedelta

from repliz_client import HEADERS, BASE

WIB = timezone(timedelta(hours=7))

FB_DAS_ID = '6a3b41e1c5ff4ce3a327543e'
LOG_FILE = os.path.join(os.path.dirname(__file__), 'post_das_fb_history.json')

IMAGE_PATH = '/home/mantapman/.hermes/profiles/atun/workspace/das_fb_post.png'
ARTICLE_URL = 'https://dasindonesia.com/kapan-mobil-perlu-engine-overhaul/'

def load_history():
    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, short_desc, article_url):
    for p in history['posts']:
        if p.get('article_url') == article_url:
            return True
        words = set(short_desc.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

# Caption — 3 paragraphs, Indonesian, humanis
caption = """Mobil Anda mulai boros oli? Setiap 500-1000 km harus nambah? Itu bukan hal yang bisa dianggap sepele. Bisa jadi ring piston atau silinder mesin sudah aus dan butuh tindakan lebih serius.

Engine overhaul atau turun mesin memang terdengar menakutkan. Tapi kalau ditunda-tunda, kerusakannya bisa makin parah dan biaya perbaikannya membengkak. Ada 6 tanda utama yang wajib Anda waspadai: asap knalpot biru, tenaga mobil luntur, suara mesin kasar, oli bercampur air, konsumsi BBM melonjak, dan kompresi mesin turun drastis.

Jangan tunggu sampai mesin benar-benar mati. Di DAS Bengkel Indonesia, kami spesialis handling engine overhaul dengan standar presisi tinggi. Yuk konsultasi gratis — baca artikel lengkapnya di bawah ini 👇"""

short_desc = caption.split('\n\n')[0][:100]
history = load_history()

if is_duplicate(history, short_desc, ARTICLE_URL):
    print(f'❌ DUPLICATE: {ARTICLE_URL}')
    sys.exit(1)

# Check existing posts for today
existing_slots = [p for p in history['posts'] if p.get('date') == '2026-07-15']
print(f'Existing posts today: {len(existing_slots)}')
for p in existing_slots:
    print(f'  - {p.get("time")}: {p.get("article_url")}')

# Try 17:00 first, if taken use next slot
target_time = '17:00'
if any(p.get('time') == target_time for p in existing_slots):
    print(f'Slot {target_time} WIB already taken, using next slot...')
    # Check 20:00
    target_time = '20:00' if not any(p.get('time') == '20:00' for p in existing_slots) else '23:00'

# Read & encode image
img_url = upload_image_to_server(IMAGE_PATH)
# FIX 21/08: no base64 — image via server OpenClaw

# Schedule time
now = datetime.now(WIB)
h, m = target_time.split(':')
schedule_at = now.replace(hour=int(h), minute=int(m), second=0, microsecond=0)
# If already past this time, it'll be scheduled for future slot
if schedule_at <= now:
    schedule_at = schedule_at.replace(day=now.day + 0)  # keep same day but future

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', '?')

        history['posts'].append({
            'date': schedule_at.strftime('%Y-%m-%d'),
            'time': target_time,
            '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'   Slot: {target_time} WIB')
        print(f'   Artikel: {ARTICLE_URL}')
except urllib.error.HTTPError as e:
    err = e.read().decode()
    print(f'❌ ERROR {e.code}: {err[:500]}')
    sys.exit(1)

