#!/usr/bin/env python3
"""
Modul bantu: batasi caption Threads ≤500 karakter (batas API Threads).
Import di script generator: dari pangkas_threads import batasi
"""
import re

LIMIT = 500


def batasi(text: str, limit: int = LIMIT) -> str:
    """Pastikan caption ≤ limit. Pertahankan link + ajakan + hashtag (maks 4)."""
    text = (text or "").strip()
    if len(text) <= limit:
        return text
    # hashtag di akhir
    tag_match = re.search(r'(\n\s*#[^\n]*(?:\s+#[^\n]*)*)\s*$', text)
    tags, body = "", text
    if tag_match:
        tags = tag_match.group(1).strip()
        body = text[:tag_match.start()].strip()
    tag_list = re.findall(r'#\w+', tags)
    if tag_list:
        tags = " ".join(tag_list[:4])
    # link
    link_match = re.search(r'https?://\S+', body)
    link = link_match.group(0) if link_match else ""
    # ajakan
    ajakan = ""
    for pat in [r'[^\n]*komentar[^\n]*', r'[^\n]*diskusi[^\n]*', r'[^\n]*pendapat[^\n]*', r'[^\n]*cerita[^\n]*']:
        m = re.findall(pat, body, re.I)
        if m:
            ajakan = m[-1].strip()
            break
    extra = len(link) + len(ajakan) + len(tags) + 8
    budget = max(limit - extra, 100)
    lines = [l for l in body.split("\n") if l.strip()]
    inti = [l for l in lines if not (link and link in l) and not (ajakan and ajakan[:30] in l)]
    core = "\n".join(inti).strip()
    if len(core) > budget:
        head_len = int(budget * 0.55)
        tail_len = int(budget * 0.40)
        head = core[:head_len].rsplit(" ", 1)[0]
        tail = core[-tail_len:]
        tail = tail.split(" ", 1)[-1] if " " in tail else tail
        core = head + "\n…\n" + tail
        if len(core) > budget:
            core = core[:budget].rsplit(" ", 1)[0]
    parts = [core] + ([link] if link else []) + ([ajakan] if ajakan else []) + ([tags] if tags else [])
    hasil = "\n\n".join(parts)
    if len(hasil) > limit:
        hasil = hasil[:limit - 1].rsplit(" ", 1)[0] + "…"
    return hasil
