#!/usr/bin/env python3
"""
DAS TikTok Crosspost — ambil video dari Repliz (konten FB DAS, sumber TikTok),
re-host ke WP DAS (URL permanen), lalu schedule ke seluruh akun DAS di Repliz
(Threads/IG DAS INDONESIA). 1 video/hari, jam 17:00 WIB.
"""
import json, os, re, sys, urllib.request, urllib.error
from datetime import datetime, timedelta, timezone

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

WIB = timezone(timedelta(hours=7))
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STAGING_FILE = os.path.join(BASE_DIR, 'das_crosspost_staging.json')
HIST_FILE = os.path.join(BASE_DIR, 'das_crosspost_history.json')
VIDEO_DIR = os.path.join(BASE_DIR, 'das_crosspost_videos')

# Akun Repliz
DAS_FB = ACC.DAS_FB            # sumber konten (FB DAS)
DAS_THREADS = ACC.DAS_THREADS  # target crosspost (DAS INDONESIA = Threads/IG)

# WP DAS
WP_URL = "https://dasindonesia.com"
WP_USER = "bambangbot"
WP_APP_PASS = "VzXR 72KF NJWn XxHI MhJN B9Hs"

POST_TIME = "17:00"  # WIB


def wp_auth_header():
    import base64
    token = f"{WP_USER}:{WP_APP_PASS}".encode()
    return "Basic " + base64.b64encode(token).decode()


def upload_video_to_wp(filepath: str, filename: str) -> str:
    """Upload mp4 ke WP media library, return URL."""
    with open(filepath, "rb") as f:
        video_data = f.read()
    boundary = "----WebKitFormBoundary" + os.urandom(8).hex()
    body = []
    body.append(f"--{boundary}".encode())
    body.append(f'Content-Disposition: form-data; name="file"; filename="{filename}"'.encode())
    body.append(b"Content-Type: video/mp4")
    body.append(b"")
    body.append(video_data)
    body.append(f"--{boundary}--".encode())
    body.append(b"")
    headers = {
        "Authorization": wp_auth_header(),
        "Content-Type": f"multipart/form-data; boundary={boundary}",
        "User-Agent": "Mozilla/5.0",
    }
    req = urllib.request.Request(
        f"{WP_URL}/wp-json/wp/v2/media",
        data=b"\r\n".join(body),
        headers=headers,
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as r:
            resp = json.loads(r.read())
            return resp.get("source_url", "")
    except urllib.error.HTTPError as e:
        print(f"    ⚠️ WP upload HTTP {e.code}: {e.read().decode()[:200]}")
        return ""
    except Exception as e:
        print(f"    ⚠️ WP upload gagal: {e}")
        return ""


def download_video(url: str, dest: str) -> bool:
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            data = r.read()
        with open(dest, "wb") as f:
            f.write(data)
        return True
    except Exception as e:
        print(f"    ⚠️ Download gagal: {e}")
        return False


def ringkas_caption(desc: str, max_len: int = 480) -> str:
    """Buang hashtag, rapikan, potong di batas kalimat kalau kepanjangan."""
    # buang hashtags
    text = re.sub(r'#\w+', '', desc)
    text = re.sub(r'\s+', ' ', text).strip()
    if len(text) <= max_len:
        return text
    # potong di kalimat terakhir yang muat
    cut = text[:max_len]
    last = cut.rfind('. ')
    if last > max_len * 0.6:
        return cut[:last + 1]
    last_space = cut.rfind(' ')
    return cut[:last_space] + "…"


def load_json(path, default):
    if os.path.exists(path):
        with open(path) as f:
            return json.load(f)
    return default


def save_json(path, data):
    with open(path, 'w') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)


def get_das_videos(client):
    """Ambil semua konten video dari akun FB DAS di Repliz."""
    vids = []
    for page in range(1, 4):
        r = client.get(f'/public/content?accountId={DAS_FB}&page={page}&limit=50')
        docs = r.get('docs', r.get('data', []))
        for d in docs:
            if d.get('type') == 'video':
                media = next((m for m in (d.get('medias') or []) if m.get('type') == 'video'), None)
                if media and media.get('url'):
                    vids.append({
                        'id': d['id'],
                        'desc': d.get('description') or '',
                        'url': media['url'],
                        'thumb': media.get('thumbnail', ''),
                    })
        if len(docs) < 50:
            break
    return vids


def main(action, video_ids=None):
    client = ReplizClient()
    os.makedirs(VIDEO_DIR, exist_ok=True)

    if action == 'stage':
        # 1) ambil video, 2) download, 3) upload WP, 4) simpan staging
        vids = get_das_videos(client)
        print(f"📹 Ditemukan {len(vids)} video DAS di Repliz")

        hist = load_json(HIST_FILE, {'posts': []})
        used = {p['video_id'] for p in hist['posts']}
        staging = load_json(STAGING_FILE, {'items': []})
        staged_ids = {s['video_id'] for s in staging['items']}

        todo = [v for v in vids if v['id'] not in used and v['id'] not in staged_ids]
        if video_ids:
            todo = [v for v in todo if v['id'] in video_ids]
        print(f"🎯 Perlu di-stage: {len(todo)} video")
        if not todo:
            print("Semua sudah ter-stage/terpakai. Jalankan 'schedule' kalau staging ada.")
            return 0

        for i, v in enumerate(todo, 1):
            fname = f"das_{v['id'].split('_')[-1]}.mp4"
            fpath = os.path.join(VIDEO_DIR, fname)
            print(f"[{i}/{len(todo)}] {v['desc'][:50].strip()}…")
            if not os.path.exists(fpath) or os.path.getsize(fpath) < 1000:
                print("    ⬇️ Download…")
                if not download_video(v['url'], fpath):
                    print("    ❌ Skip (download gagal)")
                    continue
            print(f"    ✅ Lokal: {os.path.getsize(fpath)//1024} KB")
            print("    ☁️ Upload ke WP DAS…")
            wp_url = upload_video_to_wp(fpath, fname)
            if not wp_url:
                print("    ❌ Skip (WP upload gagal)")
                continue
            print(f"    ✅ WP URL: {wp_url}")
            staging['items'].append({
                'video_id': v['id'],
                'desc': v['desc'],
                'wp_url': wp_url,
                'thumb': v['thumb'],
                'caption': ringkas_caption(v['desc']),
            })
            save_json(STAGING_FILE, staging)
        print(f"\n📦 Staging siap: {len(staging['items'])} item -> {STAGING_FILE}")
        return 0

    elif action == 'schedule':
        staging = load_json(STAGING_FILE, {'items': []})
        items = staging['items']
        if video_ids:
            items = [s for s in items if s['id'] in video_ids]
        print(f"📅 Akan di-schedule: {len(items)} video")
        if not items:
            print("Staging kosong. Jalankan 'stage' dulu.")
            return 1

        hist = load_json(HIST_FILE, {'posts': []})
        used = {p['video_id'] for p in hist['posts']}
        todo = [s for s in items if s['video_id'] not in used]

        # mulai besok jam 17:00 WIB, 1 video/hari
        start = datetime.now(WIB) + timedelta(days=1)
        if start.hour >= 17:
            start = start + timedelta(days=1)
        results = {}
        for i, s in enumerate(todo):
            day = start + timedelta(days=i)
            at = f"{day.strftime('%Y-%m-%d')}T{POST_TIME}:00+07:00"
            caption = s['caption']
            print(f"\n📅 {at} — {s['video_id']}")
            print(f"   Caption ({len(caption)} char): {caption[:80]}…")
            r = client.create_schedule(
                DAS_THREADS, caption, at,
                title="Video DAS", topic="Otomotif", type_="video",
                medias=[{"type": "video", "url": s['wp_url'], "thumbnail": s['thumb']}],
            )
            sid = r.get('scheduleId') or r.get('_id') or r.get('id')
            ok = bool(sid)
            results[s['video_id']] = ('✅' if ok else '❌', r)
            print(f"   → {'✅' if ok else '❌'} {r}")
            if ok:
                hist['posts'].append({
                    'video_id': s['video_id'],
                    'schedule_id': sid,
                    'schedule_at': at,
                    'wp_url': s['wp_url'],
                    'caption': caption,
                })
                save_json(HIST_FILE, hist)

        ok_count = sum(1 for v in results.values() if v[0] == '✅')
        print(f"\n🏁 Selesai: {ok_count}/{len(todo)} schedule dibuat. History: {HIST_FILE}")
        return 0

    elif action == 'list':
        vids = get_das_videos(client)
        for i, v in enumerate(vids, 1):
            print(f"{i}. {v['id']}")
            print(f"   {v['desc'][:80]}")
        return 0

    else:
        print("Usage: das_tiktok_crosspost.py [stage|schedule|list] [video_id,...]")
        return 1


if __name__ == '__main__':
    action = sys.argv[1] if len(sys.argv) > 1 else 'list'
    ids = sys.argv[2].split(',') if len(sys.argv) > 2 else None
    sys.exit(main(action, ids))
