"""Workflow discovery and parsing — loads workflow definitions from YAML files."""

from __future__ import annotations

from pathlib import Path

import yaml
from pydantic import BaseModel, Field

BUILTIN_DIR = Path(__file__).parent / "builtin"


class WorkflowStep(BaseModel):
    name: str
    type: str = "skill"             # skill | confirm | action | condition
    skill: str | None = None
    action: str | None = None
    inputs: dict = Field(default_factory=dict)
    outputs_key: str | None = None
    message: str | None = None      # for confirm steps
    condition: str | None = None    # for condition steps
    on_true: str | None = None      # step name to jump to
    on_false: str | None = None


class WorkflowDefinition(BaseModel):
    name: str
    version: str = "1.0"
    description: str = ""
    inputs: list[str] = Field(default_factory=list)
    steps: list[WorkflowStep] = Field(default_factory=list)
    source_path: str | None = None


def parse_workflow_file(path: Path) -> WorkflowDefinition:
    """Parse a YAML workflow definition file."""
    data = yaml.safe_load(path.read_text())
    steps = [WorkflowStep(**s) for s in data.get("steps", [])]
    return WorkflowDefinition(
        name=data.get("name", path.stem),
        version=data.get("version", "1.0"),
        description=data.get("description", ""),
        inputs=data.get("inputs", []),
        steps=steps,
        source_path=str(path),
    )


def discover_workflows(project_dir: str | Path | None = None) -> dict[str, WorkflowDefinition]:
    """Load workflows from built-in, global, and project directories. Last wins."""
    workflows: dict[str, WorkflowDefinition] = {}

    # 1. Built-in workflows
    if BUILTIN_DIR.is_dir():
        for f in sorted(BUILTIN_DIR.glob("*.yaml")):
            wf = parse_workflow_file(f)
            workflows[wf.name] = wf

    # 2. Global user workflows
    global_dir = Path.home() / ".loom" / "workflows"
    if global_dir.is_dir():
        for f in sorted(global_dir.glob("*.yaml")):
            wf = parse_workflow_file(f)
            workflows[wf.name] = wf

    # 3. Project-local workflows
    if project_dir:
        project_wf = Path(project_dir) / ".loom" / "workflows"
        if project_wf.is_dir():
            for f in sorted(project_wf.glob("*.yaml")):
                wf = parse_workflow_file(f)
                workflows[wf.name] = wf

    return workflows


def load_workflow(name: str, project_dir: str | Path | None = None) -> WorkflowDefinition:
    """Load a single workflow by name. Raises LookupError if not found."""
    workflows = discover_workflows(project_dir)
    if name not in workflows:
        raise LookupError(f"Workflow not found: {name}")
    return workflows[name]
