"""
BSS Skill: Meeting Notes Structurer
Parses raw meeting notes from PROMPT and outputs a structured summary:
attendees, action items (with owner + deadline), decisions, deferred topics.
"""
import re

text = PROMPT  # injected by BIBIVIDI sandbox wrapper

# ── Meeting metadata ──────────────────────────────────────────────────────────

def get_title(txt):
    """First non-empty, non-header-ish, non-instruction line is the meeting title."""
    for line in txt.splitlines():
        line = line.strip()
        if not line:
            continue
        # Skip section headers and user instructions
        if re.match(
            r'(?:attendees?|participants?|date|agenda|notes?|présents?|'
            r'structure|summarize|résume|analyse|please|voici)\s*[:\-–\s]',
            line, re.IGNORECASE,
        ):
            continue
        # Skip lines that are only an instruction verb at the start
        if re.match(r'^(?:structure|summarize|clean|résume|analyse|please|voici)\b', line, re.IGNORECASE):
            continue
        if 4 < len(line) <= 80:
            return line
    return ''


def get_date(txt):
    m = re.search(
        r'\b(\d{4}-\d{2}-\d{2}'
        r'|\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4}'
        r'|\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec'
        r'|jan|fév|mars|avr|mai|juin|juil|août|sep|oct|nov|déc)[a-z]*\.?\s*\d{4})\b',
        txt[:600], re.IGNORECASE,
    )
    return m.group(1) if m else ''


def get_attendees(txt):
    m = re.search(
        r'(?:attendees?|participants?|présents?|invités?|present)\s*[:\-–]\s*([^\n]{2,}(?:\n(?!\n)[^\n]{1,60})*)',
        txt, re.IGNORECASE,
    )
    if m:
        block = m.group(1)
        names = re.split(r'[,;\n]+', block)
        return [n.strip() for n in names if n.strip() and 1 < len(n.strip()) < 60][:12]
    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|\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(txt):
    """
    Detects lines of the form:
      ACTION [owner]: task [by date]
      TODO: task
      @owner task
      [ ] task (owner)
      - Name will/doit/shall task
    """
    actions = []
    for line in txt.splitlines():
        line = line.strip()
        owner, task, deadline = '', '', ''

        # Explicit ACTION / TODO keyword
        m = re.match(
            r'(?:action|todo|tâche|à faire)\s*(?:[\-–:]\s*)?'
            r'(?:\[([^\]]+)\]\s*)?[:\-–]?\s*(.{5,})',
            line, re.IGNORECASE,
        )
        if m:
            owner = m.group(1) or ''
            task  = m.group(2).strip()

        # @mention
        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()

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

        # "Name will/doit task"
        elif re.match(r'[-•]?\s*([\w\s]{2,25})\s+(?:will|va|doit|must|shall|devra)\s+(.{5,})', line, re.IGNORECASE):
            m2 = re.match(r'[-•]?\s*([\w\s]{2,25})\s+(?:will|va|doit|must|shall|devra)\s+(.{5,})', line, re.IGNORECASE)
            owner = m2.group(1).strip()
            task  = f'{m2.group(1).strip()} {m2.group(2).strip()}'

        if task:
            deadline = parse_deadline(task)
            task = DEADLINE_RE.sub('', task).strip().rstrip(',').strip()
            if len(task) > 5:
                actions.append({
                    'owner': owner.strip()[:40],
                    'task': task[:120],
                    'deadline': deadline[:30],
                })

    return actions[:15]


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

DECISION_RE = re.compile(
    r'(?:decided?|agreed?|approved?|confirmed?|validated?|resolved?|'
    r'décidé|convenu|approuvé|validé|résolu)\s*[:\-–]?\s*(.{5,})',
    re.IGNORECASE,
)


def extract_decisions(txt):
    items = []
    for m in DECISION_RE.finditer(txt):
        item = m.group(1).strip()[:130]
        if len(item) > 5:
            items.append(item)
    return list(dict.fromkeys(items))[:8]


# ── Deferred topics ───────────────────────────────────────────────────────────

DEFERRED_RE = re.compile(
    r'(?:deferred?|postponed?|next meeting|tabled?|'
    r'reporté|prochaine réunion|à reporter|à l[ae] prochaine)\s*[:\-–]?\s*(.{5,})',
    re.IGNORECASE,
)


def extract_deferred(txt):
    items = []
    for m in DEFERRED_RE.finditer(txt):
        item = m.group(1).strip()[:120]
        if len(item) > 5:
            items.append(item)
    return list(dict.fromkeys(items))[:5]


# ── Parse & output ────────────────────────────────────────────────────────────
title     = get_title(text)
date      = get_date(text)
attendees = get_attendees(text)
actions   = extract_actions(text)
decisions = extract_decisions(text)
deferred  = extract_deferred(text)

lines = ['=== BIBIVIDI: MEETING NOTES STRUCTURED ===']
if title:
    lines.append(f'Meeting  : {title}')
if date:
    lines.append(f'Date     : {date}')
if attendees:
    lines.append(f'Attendees: {", ".join(attendees)}')

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

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

if deferred:
    lines.append('\n[DEFERRED TO NEXT MEETING]')
    for d in deferred:
        lines.append(f'  - {d}')

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

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