"""
BSS Skill: Project Status Condenser
Parses weekly project status reports, sprint reviews, and standup notes,
extracting RAG status, completed work, blockers, and next steps.
Reduces status reports by 70-85%.
"""
import re
from collections import defaultdict

text = PROMPT  # injected by BIBIVIDI sandbox wrapper


# ── RAG / status detection ─────────────────────────────────────────────────────

RAG_PATTERNS = [
    ('RED',   re.compile(
        r'\b(?:red|rouge|critical|critique|blocked|bloqué|at[\s\-]risk|en\s+danger|stop|arrêt)\b',
        re.IGNORECASE,
    )),
    ('AMBER', re.compile(
        r'\b(?:amber|yellow|jaune|warning|avertissement|concern|attention|delay|retard|watch)\b',
        re.IGNORECASE,
    )),
    ('GREEN', re.compile(
        r'\b(?:green|vert|on[\s\-]track|dans\s+les\s+temps|good|bien|ok|nominal|healthy)\b',
        re.IGNORECASE,
    )),
]

STATUS_SECTION_RE = re.compile(
    r'(?:overall\s+)?(?:status|statut|état)\s*[:\-]?\s*'
    r'(red|rouge|amber|yellow|jaune|green|vert|on[\s\-]track|blocked|bloqué|at[\s\-]risk)',
    re.IGNORECASE,
)


def detect_rag(txt):
    # Explicit status line first
    m = STATUS_SECTION_RE.search(txt)
    if m:
        val = m.group(1).lower()
        if re.match(r'red|rouge|blocked|bloqué|at[\s\-]risk', val):
            return 'RED'
        if re.match(r'amber|yellow|jaune|concern|delay', val):
            return 'AMBER'
        if re.match(r'green|vert|on[\s\-]track', val):
            return 'GREEN'

    # Count RAG keywords
    counts = {}
    for label, pattern in RAG_PATTERNS:
        counts[label] = len(pattern.findall(txt))

    if counts.get('RED', 0) > 0:
        return 'RED'
    if counts.get('AMBER', 0) > counts.get('GREEN', 0):
        return 'AMBER'
    if counts.get('GREEN', 0) > 0:
        return 'GREEN'
    return None


# ── Section extraction ─────────────────────────────────────────────────────────

# Maps of section header patterns → canonical name
SECTION_MAP = [
    ('completed',    re.compile(
        r'^(?:completed?|done|accompli|terminé|finished|livré|shipped|réalisé|achievements?)',
        re.IGNORECASE,
    )),
    ('in_progress',  re.compile(
        r'^(?:in[\s\-]?progress|wip|en\s+cours|current|ongoing|this\s+(?:week|sprint|period))',
        re.IGNORECASE,
    )),
    ('blockers',     re.compile(
        r'^(?:blockers?|impediments?|issues?|risques?|risks?|problèmes?|obstacles?|concerns?)',
        re.IGNORECASE,
    )),
    ('next_steps',   re.compile(
        r'^(?:next\s+(?:steps?|week|sprint|actions?)|upcoming|à\s+venir|prochaine?s?\s+'
        r'(?:étapes?|actions?|sprint)|plan)',
        re.IGNORECASE,
    )),
    ('metrics',      re.compile(
        r'^(?:metrics?|kpis?|numbers?|chiffres?|stats?|velocity|vélocité|burndown|progress)',
        re.IGNORECASE,
    )),
]


def _strip_bullet(line):
    return re.sub(r'^[-•*✓✗→>]\s+', '', line).strip()


def extract_sections(txt):
    """
    Split the report into named sections by scanning for header lines.
    Returns dict: section_name → list[str items]
    """
    sections = defaultdict(list)
    current_section = 'misc'
    lines = txt.splitlines()

    for line in lines:
        stripped = line.strip()
        if not stripped:
            continue

        # Detect section header (short line ending in : or all-caps or markdown heading)
        is_header = (
            len(stripped) <= 60
            and (
                stripped.endswith(':')
                or stripped.startswith('#')
                or stripped.isupper()
            )
        )

        if is_header:
            header_clean = stripped.lstrip('#').rstrip(':').strip()
            matched = False
            for canon, pattern in SECTION_MAP:
                if pattern.match(header_clean):
                    current_section = canon
                    matched = True
                    break
            if not matched:
                current_section = 'misc'
            continue

        # Content line
        content = _strip_bullet(stripped)
        if len(content) >= 10:
            sections[current_section].append(content[:200])

    return sections


def extract_bullet_blocks(txt):
    """
    Fallback: scan for keyword-prefixed bullet blocks like
    'Completed: <text>' or '✓ <text>'.
    """
    sections = defaultdict(list)

    INLINE_PREFIX = re.compile(
        r'^(?:'
        r'(done|completed?|finished|accompli|terminé)\s*[:\-]\s*(.+)'
        r'|(blocked?|blocker|impediment|bloqué)\s*[:\-]\s*(.+)'
        r'|(next|upcoming|à\s+venir)\s*[:\-]\s*(.+)'
        r'|(in[\s\-]?progress|en\s+cours|wip)\s*[:\-]\s*(.+)'
        r')',
        re.IGNORECASE,
    )

    for line in txt.splitlines():
        line = line.strip()
        m = INLINE_PREFIX.match(line)
        if m:
            if m.group(1):
                sections['completed'].append(m.group(2)[:200])
            elif m.group(3):
                sections['blockers'].append(m.group(4)[:200])
            elif m.group(5):
                sections['next_steps'].append(m.group(6)[:200])
            elif m.group(7):
                sections['in_progress'].append(m.group(8)[:200])
            continue

        # Check-mark bullets → completed
        if re.match(r'^[✓✔✅]\s+', line):
            content = re.sub(r'^[✓✔✅]\s+', '', line).strip()
            if len(content) >= 10:
                sections['completed'].append(content[:200])

        # X-mark bullets → blockers
        elif re.match(r'^[✗✘❌🚫]\s+', line):
            content = re.sub(r'^[✗✘❌🚫]\s+', '', line).strip()
            if len(content) >= 10:
                sections['blockers'].append(content[:200])

    return sections


# ── Project / period meta-data ─────────────────────────────────────────────────

def extract_project_name(txt):
    # "Project: Foo" / "Project Name: Foo" / "Projet: Foo"
    m = re.search(
        r'(?:project(?:\s+name)?|projet|team|équipe)\s*[:\-]\s*([^\n]{3,50})',
        txt, re.IGNORECASE,
    )
    if m:
        return m.group(1).strip()
    return None


def extract_period(txt):
    # "Week of ...", "Sprint 12", "Period: Q2 2026", etc.
    for pat in [
        r'(?:week\s+of|semaine\s+du)\s+([^\n]{3,30})',
        r'(?:sprint)\s+(\d+(?:\s+[-–]\s+[^\n]{3,30})?)',
        r'(?:period|période)\s*[:\-]\s*([^\n]{3,30})',
        r'(?:Q[1-4]\s+\d{4})',
        r'(?:\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4}\s*[-–to à]+\s*\d{1,2}[/.\-]\d{1,2}[/.\-]\d{2,4})',
    ]:
        m = re.search(pat, txt, re.IGNORECASE)
        if m:
            return m.group(0)[:40] if not m.lastindex else m.group(1)[:40]
    return None


# ── Metric extraction ─────────────────────────────────────────────────────────

def extract_metrics(txt):
    """Pull numeric metrics: velocity, % complete, open tickets, etc."""
    metrics = []
    METRIC_RE = re.compile(
        r'(?:'
        r'(velocity|vélocité|burndown|burn[\s\-]down)\s*[:\-]?\s*(\d+(?:\.\d+)?(?:\s*(?:pts?|points?|sp))?)'
        r'|(\d+(?:\.\d+)?)\s*%\s*(?:complete|terminé|done|achevé|progress)'
        r'|(open|new|closed|fermé|ouvert)\s+(?:issues?|tickets?|bugs?)\s*[:\-]?\s*(\d+)'
        r'|(\d+)\s*(?:tasks?|stories?|tickets?)\s+(?:completed?|done|closed)'
        r')',
        re.IGNORECASE,
    )
    for m in METRIC_RE.finditer(txt):
        metrics.append(m.group(0).strip())
        if len(metrics) >= 5:
            break
    return metrics


# ── Main ───────────────────────────────────────────────────────────────────────

project = extract_project_name(text)
period  = extract_period(text)
rag     = detect_rag(text)
metrics = extract_metrics(text)

sections = extract_sections(text)

# Supplement with inline-prefix / emoji parsing when sections are sparse
if sum(len(v) for v in sections.values()) < 3:
    inline = extract_bullet_blocks(text)
    for k, v in inline.items():
        sections[k].extend(v)

lines = ['=== BIBIVIDI: PROJECT STATUS ===']
if project:
    lines.append(f'Project : {project}')
if period:
    lines.append(f'Period  : {period}')
if rag:
    lines.append(f'Status  : {rag}')

if metrics:
    lines.append('\n[METRICS]')
    for m in metrics:
        lines.append(f'  {m}')

for section_key, label in [
    ('completed',   'COMPLETED'),
    ('in_progress', 'IN PROGRESS'),
    ('blockers',    'BLOCKERS'),
    ('next_steps',  'NEXT STEPS'),
]:
    items = sections.get(section_key, [])
    if not items:
        # also check misc for fallback
        continue
    lines.append(f'\n[{label}]')
    for item in items[:8]:
        lines.append(f'  - {item}')

# If no sections extracted at all, emit misc
misc = sections.get('misc', [])
if not any(sections.get(k) for k in ('completed', 'in_progress', 'blockers', 'next_steps')) and misc:
    lines.append('\n[NOTES]')
    for item in misc[:10]:
        lines.append(f'  - {item}')

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

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