#!/usr/bin/env python3
"""Shared MLO verb/object extraction helpers."""

from __future__ import annotations

import re

from blooms import BLOOMS_VERBS, classify_blooms


_OBJECTIVE_PREFIX_RE = re.compile(
    r"^(?:CLO-?\d+|MLO-?\d+|M\d+[\.\d]*|[\d]+[\.\d]*)\s*[:\-\s]\s*",
    flags=re.IGNORECASE,
)
_LEARNER_LEADIN_RE = re.compile(
    r"^(?:by the end of (?:this )?(?:course|module|lesson|unit)[^,]*,\s*)?"
    r"(?:students?|learners?)\s+(?:will\s+|can\s+)?(?:be able to\s+)?",
    flags=re.IGNORECASE,
)


def _normalize_objective(text: str) -> str:
    cleaned = _OBJECTIVE_PREFIX_RE.sub("", str(text or "").strip())
    cleaned = _LEARNER_LEADIN_RE.sub("", cleaned).strip()
    return re.sub(r"\s+", " ", cleaned)


def _known_bloom_verbs() -> set[str]:
    verbs = set()
    for level_verbs in BLOOMS_VERBS.values():
        verbs.update(level_verbs)
    return verbs


def _object_phrase(cleaned: str, verb: str) -> str:
    if not cleaned or not verb:
        return cleaned.strip().strip(".")
    words = cleaned.split()
    if not words:
        return ""
    return " ".join(words[1:]).strip().strip(".")


def parse_objectives(objectives: list[str]) -> list[dict]:
    """Parse objective strings into text, verb, Bloom level, and object phrase."""
    parsed = []
    known_verbs = _known_bloom_verbs()
    for objective in objectives:
        text = str(objective or "").strip()
        cleaned = _normalize_objective(text)
        verb, bloom_level = classify_blooms(cleaned)
        if bloom_level == "Unknown" and verb not in known_verbs:
            verb = ""
        parsed.append({
            "text": text,
            "verb": verb,
            "bloom_level": bloom_level,
            "object_phrase": _object_phrase(cleaned, verb),
        })
    return parsed


extract_mlos = parse_objectives
