#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TSC IG — Pasang 11 desain Instagram Post Set (zip dari Bos) ke Repliz.
Tiap hari 17:00 WIB, mulai 20/08/2026. Caption dari tsc_ig_captions.md (CTA WA 085117444417).
"""
import json, os, re, sys
from datetime import datetime, timedelta, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from repliz_client import ReplizClient, ACC

WIB = timezone(timedelta(hours=7))
ROOT = os.path.dirname(os.path.abspath(__file__))
IMG_DIR = os.path.join(ROOT, "tsc_ig_zip", "Instagram Post Set for Skin Clinic")
CAP_FILE = os.path.join(ROOT, "tsc_ig_captions.md")
LOG_FILE = os.path.join(ROOT, "tsc_ig_zip_log.txt")

START_DATE = datetime(2026, 8, 20, tzinfo=WIB)  # hari ini
HOUR = 17  # 17:00 WIB
ORDER = [1, 2, 3, 11, 5, 6, 7, 8, 9, 10, 4]  # urutan B: page 11 di posisi 4, page 4 di paling belakang (FIX Bos 20/08)

def parse_captions(path):
    """Parse tsc_ig_captions.md -> {1: caption, 2: caption, ...}"""
    txt = open(path, encoding="utf-8").read()
    # Potong bagian penjelasan di atas (sampai '## Page 1')
    parts = re.split(r"^## Page (\d+)", txt, flags=re.M)
    caps = {}
    # parts[0] = header, lalu bergantian nomor & isi
    for i in range(1, len(parts), 2):
        num = int(parts[i])
        body = parts[i+1].strip() if i+1 < len(parts) else ""
        # buang baris komentar "## Page N (posisi X)" — ambil sampai sebelum "---" berikutnya
        body = body.split("\n---")[0].strip()
        caps[num] = body
    return caps

def main():
    caps = parse_captions(CAP_FILE)
    client = ReplizClient()
    log_lines = []
    ok = fail = 0

    print(f"📅 Jadwal 11 hari mulai {START_DATE.strftime('%d/%m/%Y')} 17:00 WIB — IG The Skin Code Clinic")
    for i, page in enumerate(ORDER):
        tgl = START_DATE + timedelta(days=i)
        img_path = os.path.join(IMG_DIR, f"{page}.png")
        caption = caps.get(page, "")
        if not os.path.exists(img_path):
            print(f"  ❌ [{i+1}/11] Page {page}: gambar tidak ada — {img_path}")
            fail += 1
            continue
        if not caption:
            print(f"  ❌ [{i+1}/11] Page {page}: caption kosong")
            fail += 1
            continue

        schedule_at = f"{tgl.date().isoformat()}T{HOUR:02d}:00:00+07:00"
        title = f"TSC IG Page {page}"
        print(f"  [{i+1}/11] {tgl.strftime('%d/%m/%Y')} 17:00 WIB — {img_path.split('/')[-1]}")

        res = client.schedule_image(
            ACC.TSC_IG, caption, schedule_at, img_path,
            filename=f"tsc_ig_page{page}.png", title=title, topic="Instagram Post Set"
        )
        if res and (res.get("ok") or res.get("scheduleId")):
            sid = res.get("scheduleId") or res.get("id")
            print(f"      ✅ ID: {sid}")
            ok += 1
            log_lines.append(f"OK {schedule_at} | Page {page} | {sid}")
        else:
            print(f"      ❌ {json.dumps(res, ensure_ascii=False)[:200]}")
            fail += 1
            log_lines.append(f"FAIL {schedule_at} | Page {page} | {json.dumps(res, ensure_ascii=False)[:200]}")

    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(f"\n=== RUN {datetime.now(WIB).isoformat()} — {ok} OK, {fail} gagal ===\n")
        f.write("\n".join(log_lines) + "\n")
    print(f"\n📊 Total: {ok} OK, {fail} gagal")

if __name__ == "__main__":
    main()
