"""
BSS Skill: Batch Translation Condenser
Detects repetitive "translate X to Y" prompts with multiple items,
strips the boilerplate, and outputs a compact numbered list with a
single shared instruction — dramatically reducing token count.
"""
import re

text = PROMPT

# ── Detect target language ────────────────────────────────────────────────────
lang_match = re.search(
    r"(?:translate|tradui[st]|übersetz)[^:.\n]{0,60}"
    r"(?:to|en|auf|in|into|vers)\s+([A-Za-zÀ-ÿ]+)",
    text, re.IGNORECASE
)
target_lang = lang_match.group(1).strip() if lang_match else "the target language"

# ── Detect source language (optional) ────────────────────────────────────────
src_match = re.search(
    r"(?:from|de|aus|depuis)\s+([A-Za-zÀ-ÿ]+)\s+(?:to|en|auf|in|into|vers)",
    text, re.IGNORECASE
)
source_lang = src_match.group(1).strip() if src_match else None

# ── Extract items to translate ────────────────────────────────────────────────

# Verbs that signal guideline/instruction lines rather than content to translate
_INSTRUCTION_VERBS = re.compile(
    r"^\s*(?:use|do not|don't|keep|preserve|avoid|ensure|review|maintain|"
    r"follow|check|note|make sure|always|never|refer|see|include|exclude|"
    r"utilise|ne pas|évite|assure|vérifie|garde|préserve)\b",
    re.IGNORECASE
)

def _is_instruction(line: str) -> bool:
    """Return True if the line looks like a guideline rather than content."""
    return bool(_INSTRUCTION_VERBS.match(line.strip()))

def _extract_list(block: str) -> list[str]:
    """Extract numbered/bulleted items from a text block, filtering instructions."""
    found = re.findall(r"^\s*(?:\d+[.)]\s*[-–]?\s*|[-•*]\s+)(.+)", block, re.MULTILINE)
    return [i.strip() for i in found if i.strip() and not _is_instruction(i)]

# Strategy 0: explicit section header ("Products:", "Items to translate:", etc.)
_SECTION_HEADER = re.compile(
    r"(?:products?|items?|texts?|strings?|titles?|entries|list|following"
    r"|produits?|éléments?|titres?|textes?)\s*(?:to\s+translate|à\s+traduire)?\s*:\s*\n",
    re.IGNORECASE
)
items: list[str] = []
section_match = _SECTION_HEADER.search(text)
if section_match:
    items = _extract_list(text[section_match.end():])

# Strategy 1: numbered/bulleted list anywhere (only if no section header found),
# filtering out instruction-like lines
if len(items) < 2:
    items = _extract_list(text)

# Strategy 2: quoted strings
if len(items) < 2:
    items = re.findall(r'["\u201c\u00ab]([^"\u201d\u00bb\n]{2,120})["\u201d\u00bb]', text)

# Strategy 3: line-by-line after the last colon/header in the prompt
if len(items) < 2:
    parts = re.split(r":\s*\n", text)
    if len(parts) >= 2:
        items = [l.strip() for l in parts[-1].splitlines()
                 if l.strip() and len(l.strip()) > 1 and not _is_instruction(l)]

# Fallback — nothing detected, pass through truncated
if len(items) < 2:
    print(text[:600])
    raise SystemExit

# Deduplicate while preserving order
seen = set()
unique_items = []
for item in items:
    item = item.strip().strip('"').strip("'")
    if item and item not in seen:
        seen.add(item)
        unique_items.append(item)

# ── Detect any tone/formality instruction ────────────────────────────────────
tone_match = re.search(
    r"(?:formal|informal|professional|casual|polite|friendly|technical|simple)",
    text, re.IGNORECASE
)
tone = f" ({tone_match.group(0)} tone)" if tone_match else ""

# ── Output ────────────────────────────────────────────────────────────────────
src_info = f" from {source_lang}" if source_lang else ""
print(f"=== BIBIVIDI BATCH TRANSLATION ===")
print(f"Task: Translate{src_info} to {target_lang}{tone}.")
print(f"Items ({len(unique_items)}):")
print()
for i, item in enumerate(unique_items, 1):
    print(f"{i}. {item}")
print()
print("Return a numbered list in the same order. No extra explanation.")
print("=== END ===")
