"""
BSS Skill: Slack Thread Distiller
Parses a Slack/Teams/Discord thread from PROMPT and outputs: participants,
topic, key decisions, action items, unresolved questions, and current state.
"""
import re

text = PROMPT  # injected by BIBIVIDI sandbox wrapper


# ── Message parsing ───────────────────────────────────────────────────────────

def parse_messages(txt):
    """
    Split a chat thread into individual messages.

    Supported formats:
      Slack copy-paste : "Username  10:32\ncontent"  (double space before time)
      Teams/IRC        : "[10:32] Username: content"
      Parenthetical    : "Username (10:32 AM): content"
      Discord bold     : "**Username**: content"
      Fallback         : "Username: content"
    """
    # Header patterns — each matches a message boundary line
    SLACK_HDR  = re.compile(r'^([\w][\w\s.\'_-]{0,40}?)\s{2,}\d{1,2}:\d{2}(?:\s*[AP]M)?\s*$', re.MULTILINE)
    TEAMS_HDR  = re.compile(r'^\[(\d{1,2}:\d{2}(?:\s*[AP]M)?)\]\s+([\w][\w\s.\'_-]{0,40}?):\s*(.+)', re.MULTILINE)
    PAREN_HDR  = re.compile(r'^([\w][\w\s.\'_-]{0,40}?)\s+\(\d{1,2}:\d{2}(?:\s*[AP]M)?\):\s*(.+)', re.MULTILINE)
    DISCORD_HDR = re.compile(r'^\*\*([\w][\w\s.\'_-]{0,40}?)\*\*:\s*(.+)', re.MULTILINE)
    FALLBACK_HDR = re.compile(r'^@?([\w][\w.\'_-]{1,30}):\s*(.{3,})', re.MULTILINE)

    lines = txt.splitlines()

    # ── Slack format: "Author  HH:MM" on its own line, content on following lines ──
    slack_hdrs = [(m.start(), m.group(1).strip()) for m in SLACK_HDR.finditer(txt)]
    if len(slack_hdrs) >= 2:
        messages = []
        for i, (hdr_pos, author) in enumerate(slack_hdrs):
            next_pos = slack_hdrs[i + 1][0] if i + 1 < len(slack_hdrs) else len(txt)
            # Content starts after the header line (find the \n after the header)
            content_start = txt.find('\n', hdr_pos)
            if content_start == -1:
                content_start = hdr_pos
            content = txt[content_start:next_pos].strip()
            if content:
                messages.append({'author': author, 'content': content})
        if messages:
            return messages

    # ── Teams/IRC: "[HH:MM] Username: content" (one line per message) ──
    teams = [(m.group(2).strip(), m.group(3).strip()) for m in TEAMS_HDR.finditer(txt)]
    if teams:
        return [{'author': a, 'content': c} for a, c in teams]

    # ── Parenthetical: "Username (HH:MM AM): content" ──
    parens = [(m.group(1).strip(), m.group(2).strip()) for m in PAREN_HDR.finditer(txt)]
    if parens:
        return [{'author': a, 'content': c} for a, c in parens]

    # ── Discord bold: "**Username**: content" ──
    discord = [(m.group(1).strip(), m.group(2).strip()) for m in DISCORD_HDR.finditer(txt)]
    if discord:
        return [{'author': a, 'content': c} for a, c in discord]

    # ── Fallback: "Username: content" ──
    return [{'author': m.group(1).strip(), 'content': m.group(2).strip()}
            for m in FALLBACK_HDR.finditer(txt)]


# ── Participants ──────────────────────────────────────────────────────────────

def get_participants(messages):
    seen = {}
    for msg in messages:
        a = msg['author']
        if a not in seen:
            seen[a] = True
    return list(seen.keys())[:10]


# ── Topic ─────────────────────────────────────────────────────────────────────

def get_topic(messages, txt):
    # Channel name on first line: #channel-name
    first_line = txt.strip().splitlines()[0] if txt.strip() else ''
    m = re.search(r'#([\w-]+)', first_line)
    if m:
        return '#' + m.group(1)
    # First non-empty message content
    for msg in messages:
        content = msg['content'].strip()
        if content:
            return content[:80]
    return ''


# ── Action items ──────────────────────────────────────────────────────────────

DEADLINE_RE = re.compile(
    r'(?:by|before|due|avant le|pour le|deadline)\s+'
    r'(\d{4}-\d{2}-\d{2}|\d{1,2}[/.\-]\d{1,2}(?:[/.\-]\d{2,4})?'
    r'|\w+day|EOD|COB|Friday|Monday|Tuesday|Wednesday|Thursday|Saturday|Sunday'
    r'|\d{1,2}\s+\w+)',
    re.IGNORECASE,
)


def parse_deadline(txt):
    m = DEADLINE_RE.search(txt)
    return m.group(1).strip() if m else ''


def extract_actions(messages):
    actions = []
    seen = set()

    for msg in messages:
        author = msg['author']
        # Process each line of the message content separately
        for line in msg['content'].splitlines():
            line = line.strip()
            if len(line) < 6:
                continue
            owner, task = '', ''

            # Explicit ACTION: [owner] task — use search to catch inline "Great! ACTION: ..."
            m = re.search(
                r'(?:action|todo|t[aâ]che|[aà] faire)\s*[:\-–]\s*'
                r'(?:([\w.]+)\s+)?(.{5,})',
                line, re.IGNORECASE,
            )
            if m:
                owner = m.group(1) or ''
                task = m.group(2).strip()

            # @username can you <task>
            elif re.match(r'@([\w.]+)\s+(?:can you|could you|please|pourriez.vous)\s+(.{5,})', line, re.IGNORECASE):
                m2 = re.match(r'@([\w.]+)\s+(?:can you|could you|please|pourriez.vous)\s+(.{5,})', line, re.IGNORECASE)
                owner = m2.group(1)
                task = m2.group(2).strip()

            # <username> will/devra <task>
            elif re.match(r'([\w.]+)\s+(?:will|va|doit|devra|shall)\s+(.{5,})', line, re.IGNORECASE):
                m2 = re.match(r'([\w.]+)\s+(?:will|va|doit|devra|shall)\s+(.{5,})', line, re.IGNORECASE)
                owner = m2.group(1)
                task = f'{m2.group(1)} {m2.group(2).strip()}'

            # Checkbox [ ] task
            elif re.match(r'\[\s*\]\s*(.{5,})', line):
                task = re.match(r'\[\s*\]\s*(.{5,})', line).group(1).strip()

            # @mention standalone
            elif re.match(r'@([\w.]+)\s+(.{5,})', line):
                m2 = re.match(r'@([\w.]+)\s+(.{5,})', line)
                owner = m2.group(1)
                task = m2.group(2).strip()

            if task:
                deadline = parse_deadline(task)
                task = DEADLINE_RE.sub('', task).strip().rstrip(',').strip()
                if len(task) > 5:
                    key = task[:60].lower()
                    if key not in seen:
                        seen.add(key)
                        actions.append({
                            'owner': (owner or author).strip()[:40],
                            'task': task[:120],
                            'deadline': deadline[:30],
                        })

    return actions[:10]


# ── Decisions ─────────────────────────────────────────────────────────────────

DECISION_RE = re.compile(
    r'(?:'
    r'DECISION\s*:\s*(.{5,})'
    r'|(?:agreed?|convenu)\s*[:\-–]\s*(.{5,})'
    r'|✅\s*(.{5,})'
    r'|(?:decided? to|on a décidé de)\s+(.{5,})'
    r')',
    re.IGNORECASE,
)


def extract_decisions(messages):
    items = []
    seen = set()
    for msg in messages:
        for m in DECISION_RE.finditer(msg['content']):
            item = next((g.strip() for g in m.groups() if g), '')
            if len(item) > 5:
                key = item[:60].lower()
                if key not in seen:
                    seen.add(key)
                    items.append(item[:130])
    return items[:6]


# ── Current state ─────────────────────────────────────────────────────────────

def get_resolution(messages):
    non_empty = [m for m in messages if m['content'].strip()]
    last_three = non_empty[-3:] if len(non_empty) >= 3 else non_empty
    parts = []
    for msg in last_three:
        # Flatten multi-line content to a single line
        snippet = ' '.join(msg['content'].strip().splitlines())[:200]
        parts.append(f'{msg["author"]}: {snippet}')
    return '\n  '.join(parts)


# ── Unresolved questions ──────────────────────────────────────────────────────

def get_unresolved(txt):
    items = []
    seen = set()
    lines = txt.splitlines()
    for i, line in enumerate(lines):
        line = line.strip()
        # Lines ending with ? (skip very short ones)
        if line.endswith('?') and len(line) > 10:
            # Naive check: not answered in the next 3 lines
            following = ' '.join(lines[i + 1:i + 4]).lower()
            answered = bool(re.search(
                r'\b(?:yes|no|agreed|decided|will|ok|sure|oui|non|d\'accord)\b',
                following,
            ))
            if not answered:
                key = line[:60].lower()
                if key not in seen:
                    seen.add(key)
                    items.append(line[:120])
        # Explicit TBD / TO BE DECIDED markers
        m = re.search(
            r'(?:TBD|TO BE DECIDED|à décider|en attente)\s*[:\-–]?\s*(.{0,100})',
            line, re.IGNORECASE,
        )
        if m:
            label = m.group(0).strip()
            key = label[:60].lower()
            if key not in seen:
                seen.add(key)
                items.append(label[:120])

    return items[:3]


# ── Parse ─────────────────────────────────────────────────────────────────────

messages   = parse_messages(text)
topic      = get_topic(messages, text)
parts      = get_participants(messages)
decisions  = extract_decisions(messages)
actions    = extract_actions(messages)
resolution = get_resolution(messages)
unresolved = get_unresolved(text)

# ── Output ────────────────────────────────────────────────────────────────────

lines = ['=== BIBIVIDI: SLACK THREAD ===']
if topic:
    lines.append(f'Topic       : {topic}')
if parts:
    lines.append(f'Participants: {", ".join(parts)}')
lines.append(f'Messages    : {len(messages)}')

if decisions:
    lines.append('\n[DECISIONS]')
    for d in decisions:
        lines.append(f'  - {d}')

if actions:
    lines.append('\n[ACTION ITEMS]')
    for a in actions:
        parts_str = []
        if a['owner']:
            parts_str.append(a['owner'])
        parts_str.append(a['task'])
        if a['deadline']:
            parts_str.append(f'→ by {a["deadline"]}')
        lines.append(f'  - {" | ".join(parts_str)}')

if unresolved:
    lines.append('\n[UNRESOLVED]')
    for u in unresolved:
        lines.append(f'  - {u}')

if resolution:
    lines.append('\n[CURRENT STATE]')
    lines.append(f'  {resolution}')

# If no decisions and no actions, add a [SUMMARY] section for context
if not decisions and not actions:
    non_empty = [m for m in messages if m['content'].strip()]
    lines.append('\n[SUMMARY]')
    if non_empty:
        first = non_empty[0]
        lines.append(f'  First: {first["author"]}: {first["content"][:200]}')
    if len(non_empty) > 1:
        last = non_empty[-1]
        lines.append(f'  Last : {last["author"]}: {last["content"][:200]}')

lines.append(f'\n=== END (condensed from {len(text)} chars) ===')

print('\n'.join(lines))
