"""Save a structured knowledge record."""

from fliiq.runtime.knowledge.drift import compute_anchor_hash
from fliiq.runtime.knowledge.models import (
    Anchor,
    KnowledgeRecord,
    RecordType,
    SourceType,
)
from fliiq.runtime.knowledge.store import KnowledgeStore


async def handler(params: dict) -> dict:
    """Create and persist a knowledge record."""
    store = KnowledgeStore.from_fliiq_dir()

    # Build anchor if file path provided
    anchor = None
    if params.get("anchor_file"):
        line_start = None
        line_end = None
        if params.get("anchor_lines"):
            parts = params["anchor_lines"].split("-")
            line_start = int(parts[0])
            line_end = int(parts[1]) if len(parts) > 1 else line_start

        content_hash = None
        if line_start and line_end:
            try:
                content_hash = compute_anchor_hash(
                    params["anchor_file"], line_start, line_end
                )
            except FileNotFoundError:
                pass

        anchor = Anchor(
            file=params["anchor_file"],
            line_start=line_start,
            line_end=line_end,
            content_hash=content_hash,
        )

    record = KnowledgeRecord(
        type=RecordType(params["type"]),
        source=SourceType(params["source"]),
        context=params["context"],
        decision=params["decision"],
        rationale=params["rationale"],
        confidence=params.get("confidence", 0.8),
        domain=params.get("domain", ""),
        tags=params.get("tags", []),
        constraints=params.get("constraints", []),
        anchor=anchor,
        alternatives_considered=params.get("alternatives", []),
        scope=params.get("scope", "project"),
    )

    store.save(record)
    return {"id": record.id, "result": f"Knowledge record saved: {record.type.value} in {record.context}"}
