"""Pathway Store — in-memory pathway storage and serialization.

Handles saving/loading pathways to the in-memory registry and
exporting pathways as portable JSON documents.
"""

import logging
from typing import Any

from core.common import JsonObject
from core.pathways.pathway import Pathway
from core.pathways.registry import PathwayMeta, PathwayRegistry

logger = logging.getLogger(__name__)


def serialize_node(node: Any) -> JsonObject:
    """Serialize a node to a dictionary.

    Uses Pydantic's model_dump() — the node model IS the schema.
    """
    return node.model_dump(mode="json", exclude_none=True)


class PathwayStore:
    """In-memory pathway storage with serialization helpers."""

    def create_user_pathway(
        self,
        pathway: Pathway,
        *,
        source: str = "user:unknown",
        registry: PathwayRegistry,
    ) -> PathwayMeta:
        """Create a user pathway and register it."""
        pid = pathway.id

        registry.put(pid, pathway)

        meta = PathwayMeta(
            id=pid,
            name=pathway.name,
            description=pathway.description,
            source=source,
            version=None,
            doc_id=None,
            node_count=len(pathway.nodes),
        )
        registry.set_meta(pid, meta)

        logger.debug("Created pathway: %s (source=%s)", pid, source)
        return meta

    def export(
        self,
        pathway: Pathway,
        meta: PathwayMeta | None,
    ) -> JsonObject:
        """Export a pathway as a portable JSON document."""
        return {
            "format": "albusos.pathway.v1",
            "pathway": {
                "id": pathway.id,
                "name": pathway.name,
                "description": pathway.description,
                "nodes": [serialize_node(node) for node in pathway.nodes.values()],
                "connections": [
                    {"from": c.from_node, "to": c.to_node} for c in pathway.connections
                ],
                "metadata": dict(pathway.metadata),
            },
            "meta": meta.model_dump() if meta else None,
        }


__all__ = [
    "PathwayStore",
    "serialize_node",
]
