"""DAG export to JSON, DOT, and Mermaid formats."""

from __future__ import annotations

import json

from orxaq.kernel.world_dag import WorldDAG


class DAGExporter:
    """Export a World DAG to various graph formats."""

    def __init__(self, dag: WorldDAG) -> None:
        self.dag = dag

    def to_json(self, indent: int = 2) -> str:
        """Export as JSON."""
        nodes = []
        for eid, entity in sorted(self.dag._entities.items()):
            nodes.append(
                {
                    "id": eid,
                    "name": entity.name,
                    "causal_role": entity.causal_role.value,
                    "variable_type": entity.variable_type.value,
                    "domain": entity.domain,
                }
            )

        edges = []
        for edge in self.dag._edges.values():
            edges.append(
                {
                    "source": edge.source,
                    "target": edge.target,
                    "mechanism": edge.mechanism,
                    "confidence": edge.confidence,
                    "soliton_score": edge.soliton_score,
                }
            )

        return json.dumps(
            {"nodes": nodes, "edges": edges},
            indent=indent,
            sort_keys=False,
        )

    def to_dot(self, title: str = "WorldDAG") -> str:
        """Export as Graphviz DOT format."""
        lines = [f'digraph "{title}" {{']
        lines.append("  rankdir=TB;")
        lines.append('  node [shape=box, style=filled, fillcolor="#e8e8ff"];')
        lines.append("")

        for eid, entity in sorted(self.dag._entities.items()):
            label = entity.name or eid
            tooltip = entity.description or ""
            lines.append(f'  "{eid}" [label="{label}", tooltip="{tooltip}"];')

        lines.append("")
        for edge in self.dag._edges.values():
            label = edge.mechanism or ""
            conf = f"{edge.confidence:.2f}"
            lines.append(
                f'  "{edge.source}" -> "{edge.target}" [label="{label}", tooltip="conf={conf}"];'
            )

        lines.append("}")
        return "\n".join(lines)

    def to_mermaid(self) -> str:
        """Export as Mermaid flowchart syntax."""
        lines = ["graph TD"]

        for eid, entity in sorted(self.dag._entities.items()):
            label = entity.name or eid
            safe_label = label.replace('"', "'")
            lines.append(f'  {eid}["{safe_label}"]')

        for edge in self.dag._edges.values():
            label = edge.mechanism
            if label:
                safe_label = label.replace('"', "'")
                lines.append(f'  {edge.source} -->|"{safe_label}"| {edge.target}')
            else:
                lines.append(f"  {edge.source} --> {edge.target}")

        return "\n".join(lines)

    def to_dict(self) -> dict:
        """Export as a Python dict (for API responses)."""
        return dict(json.loads(self.to_json()))
