"""
Read and parse .dryft/intent.md (agent-declared plan, expected files, dependencies).
"""

import re
from pathlib import Path
from typing import TypedDict

INTENT_FILENAME = Path(".dryft") / "intent.md"


def _parse_list_lines(text: str) -> list[str]:
    out = []
    for line in text.split("\n"):
        line = re.sub(r"^\s*[-*]\s+", "", re.sub(r"^\s*\d+\.\s*", "", line)).strip()
        if line:
            out.append(line)
    return out


def _extract_section(content: str, heading: str) -> str:
    pattern = re.compile(
        r"##\s+" + re.escape(heading) + r"\s*\n([\s\S]*?)(?=##\s|$)",
        re.IGNORECASE,
    )
    m = pattern.search(content)
    return m.group(1).strip() if m else ""


class IntentData(TypedDict, total=False):
    currentTask: str
    plannedFiles: list[str]
    dependencies: list[str]
    activeChanges: str
    notes: str


def read_intent(cwd: str) -> IntentData | None:
    path = Path(cwd) / INTENT_FILENAME
    try:
        content = path.read_text(encoding="utf-8")
    except OSError:
        return None
    current_task = _extract_section(content, "Current Task")
    planned_files_text = _extract_section(content, "Planned Files")
    dependencies_text = _extract_section(content, "Dependencies")
    active_changes = _extract_section(content, "Active Changes")
    notes = _extract_section(content, "Notes")
    planned = _parse_list_lines(planned_files_text)
    deps = _parse_list_lines(dependencies_text)
    out: IntentData = {}
    if current_task:
        out["currentTask"] = current_task
    if planned:
        out["plannedFiles"] = planned
    if deps:
        out["dependencies"] = deps
    if active_changes:
        out["activeChanges"] = active_changes
    if notes:
        out["notes"] = notes
    return out if out else None
