"""Vastian Meeting Analyzer — Adaptive Parser.

Parsing utilities that detect heading patterns in meeting summaries
and split text into named sections regardless of the source format
(Teams, Pocket, manual markdown, etc.).
"""

from __future__ import annotations

import logging
import re

from .constants import HEADING_PATTERNS, HEADING_TO_SIGNAL_TYPE

logger = logging.getLogger(__name__)


def parse_adaptive(text: str) -> dict[str, str]:
    """Adaptively parse meeting text by detecting heading patterns.

    Supports multiple formats:
    - Teams summary format
    - Pocket dynamic summaries
    - Manual markdown notes
    - Plain text with colon-headers

    Args:
        text: Raw meeting summary text.

    Returns:
        Dict mapping section names to their content.
    """
    result: dict[str, str] = {}
    current_section: str | None = None
    buffer: list[str] = []

    for line in text.splitlines():
        stripped = line.strip()

        # Preserve empty lines inside content
        if not stripped:
            buffer.append(line)
            continue

        # Skip HTML aside tags
        if stripped.startswith("<aside") or stripped.endswith("</aside>"):
            continue

        heading = detect_heading(stripped)

        if heading:
            # Flush previous section
            if current_section:
                result[current_section] = "\n".join(buffer).strip()
            current_section = heading
            buffer = []
            continue

        buffer.append(line)

    # Flush final section
    if current_section:
        result[current_section] = "\n".join(buffer).strip()
    elif buffer:
        # No sections detected — treat entire text as notes
        result["notes"] = "\n".join(buffer).strip()

    return result


def detect_heading(line: str) -> str | None:
    """Detect if a line is a heading and return its canonical name.

    Args:
        line: A single stripped line of text.

    Returns:
        Canonical heading name, or ``None`` if the line is not a heading.
    """
    cleaned = line.lstrip("#").strip().strip("*").strip()

    for pattern_name, pattern in HEADING_PATTERNS.items():
        match = re.match(pattern, line)
        if match:
            if pattern_name == "emoji":
                heading_text = match.group(2).lower().strip()
            else:
                heading_text = match.group(1).lower().strip() if match.groups() else cleaned.lower()
            return HEADING_TO_SIGNAL_TYPE.get(heading_text, cleaned)

    # Direct lookup for cleaned text
    cleaned_lower = cleaned.lower()
    if cleaned_lower in HEADING_TO_SIGNAL_TYPE:
        return HEADING_TO_SIGNAL_TYPE[cleaned_lower]

    return None


def parse_meeting_summary_adaptive(text: str) -> dict[str, str]:
    """Legacy wrapper kept for backward compatibility."""
    return parse_adaptive(text)


__all__ = [
    "parse_adaptive",
    "detect_heading",
    "parse_meeting_summary_adaptive",
]
