#!/usr/bin/env python3
"""One-off: Post 1 konten LinkedIn DMark Creative — link artikel, konten UNIK."""
import urllib.request, json, os, sys
from datetime import datetime, timezone, timedelta

AUTH = 'NDY1NDYwOTg2Njpzb09vSDJJUnk2QmthSXJIU0FmMW5HbHkyUmNvaXc5Wg=='
HEADERS = {'Authorization': AUTH, 'Content-Type': 'application/json'}
BASE = 'https://api.repliz.com'
WIB = timezone(timedelta(hours=7))

DMark_LI = '6a350ecbc5ff4ce3a32299ce'
LOG_FILE = '/home/mantapman/.hermes/profiles/atun/workspace/dmark_linkedin_history.json'

ARTICLE = {
    'url': 'https://www.dmark.id/studiosoft-digital-marketing-surabaya-terbaik/',
    'title': 'StudioSoft: Digital Marketing Surabaya Terbaik',
}

CAPTION = (
    "Banyak pebisnis di Surabaya bertanya: kenapa gak semua jasa digital marketing "
    "memberi hasil yang konsisten? Jawabannya seringkali bukan di budget, tapi di "
    "strategi dan eksekusi yang terukur.\n\n"
    "StudioSoft hadir sebagai mitra yang mengedepankan pendekatan berbasis data — "
    "dari riset pasar, perancangan strategi, sampai eksekusi kampanye digital yang "
    "bisa diukur dampaknya. Ini bukan sekadar jasa, tapi kemitraan jangka panjang "
    "untuk pertumbuhan bisnis.\n\n"
    "Di artikel ini kami mengupas kenapa memilih mitra yang tepat itu penting, "
    "dan bagaimana StudioSoft membantu banyak brand mencapai target pemasaran "
    "mereka di tengah persaingan yang makin ketat. Yuk dibaca.\n\n"
    "https://www.dmark.id/studiosoft-digital-marketing-surabaya-terbaik/\n\n"
    "#DigitalMarketing #Branding #StudioSoft #DMarkCreative #Surabaya"
)

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

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

def main():
    # Sched untuk besok (hari ini udah lewat jam 11:00 WIB, skrg ~11:16 WIB)
    now = datetime.now(WIB)
    sched = (now + timedelta(days=1)).replace(hour=11, minute=0, second=0, microsecond=0)
    iso = sched.strftime('%Y-%m-%dT%H:%M:%S.000Z')

    payload = {
        'title': '',
        'description': CAPTION,
        'topic': 'Digital Marketing',
        'type': 'text',
        'medias': [],
        'meta': {
            'title': ARTICLE['title'],
            'description': f'Baca artikel selengkapnya di DMark Creative — {ARTICLE["title"]}',
            'url': ARTICLE['url']
        },
        'additionalInfo': {'isAiGenerated': False, 'isDraft': False, 'collaborators': [],
            'mentions': [], 'music': {'id': '', 'artist': '', 'name': '', 'thumbnail': ''},
            'products': [], 'tags': []},
        'replies': [],
        'accountId': DMark_LI,
        'scheduleAt': 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=60) as resp:
            result = json.loads(resp.read())
    except Exception as e:
        print(f'❌ Gagal: {e}')
        sys.exit(1)

    sid = result.get('scheduleId', result.get('id', '?'))
    print(f'✅ DMark LinkedIn — {sched.strftime("%d %b %Y %H:%M")} WIB')
    print(f'   ID: {sid}')
    print(f'   Artikel: {ARTICLE["title"]}')

    # Catat history
    h = load_history()
    h['posts'].append({
        'date': sched.strftime('%Y-%m-%d'),
        'time': '11:00',
        'platform': 'linkedin',
        'article_url': ARTICLE['url'],
        'article_title': ARTICLE['title'],
        'schedule_id': sid,
    })
    save_history(h)
    print('✅ History tercatat.')

if __name__ == '__main__':
    main()
