"""DataExporter: export MemoTrail data to JSON format."""

import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

from memotrail.storage import SQLiteStore
from memotrail.utils import get_logger

logger = get_logger("memotrail.sync.exporter")


class DataExporter:
    """Export MemoTrail data to portable JSON format."""

    def __init__(self, sqlite_store: SQLiteStore | None = None):
        self.sqlite = sqlite_store or SQLiteStore()

    def export_all(self, output_path: str | Path) -> dict:
        """Export all data to a JSON file.

        Args:
            output_path: Path for the output JSON file

        Returns:
            Summary dict with counts
        """
        data = {
            "version": "1.0.0",
            "exported_at": datetime.now(timezone.utc).isoformat(),
            "sessions": self._export_sessions(),
            "messages": self._export_messages(),
            "decisions": self._export_decisions(),
            "memories": self._export_memories(),
            "entities": self._export_entities(),
            "relations": self._export_relations(),
            "fact_history": self._export_fact_history(),
        }

        output_path = Path(output_path)
        output_path.write_text(json.dumps(data, indent=2, ensure_ascii=False))

        summary = {k: len(v) for k, v in data.items() if isinstance(v, list)}
        logger.info(f"Exported data to {output_path}: {summary}")
        return summary

    def export_project(self, project: str, output_path: str | Path) -> dict:
        """Export data for a specific project.

        Args:
            project: Project name to export
            output_path: Path for the output JSON file

        Returns:
            Summary dict with counts
        """
        sessions = self._export_sessions(project=project)
        session_ids = {s["id"] for s in sessions}

        data = {
            "version": "1.0.0",
            "exported_at": datetime.now(timezone.utc).isoformat(),
            "project": project,
            "sessions": sessions,
            "messages": [m for m in self._export_messages() if m["session_id"] in session_ids],
            "decisions": [d for d in self._export_decisions() if d["session_id"] in session_ids],
            "memories": self._export_memories(),
            "entities": self._export_entities(),
            "relations": self._export_relations(),
            "fact_history": self._export_fact_history(),
        }

        output_path = Path(output_path)
        output_path.write_text(json.dumps(data, indent=2, ensure_ascii=False))

        summary = {k: len(v) for k, v in data.items() if isinstance(v, list)}
        logger.info(f"Exported project '{project}' to {output_path}: {summary}")
        return summary

    def _export_sessions(self, project: Optional[str] = None) -> list[dict]:
        if project:
            rows = self.sqlite.conn.execute(
                "SELECT * FROM sessions WHERE project = ? ORDER BY started_at",
                (project,),
            ).fetchall()
        else:
            rows = self.sqlite.conn.execute(
                "SELECT * FROM sessions ORDER BY started_at"
            ).fetchall()
        return [dict(r) for r in rows]

    def _export_messages(self) -> list[dict]:
        rows = self.sqlite.conn.execute(
            "SELECT * FROM messages ORDER BY timestamp"
        ).fetchall()
        return [dict(r) for r in rows]

    def _export_decisions(self) -> list[dict]:
        rows = self.sqlite.conn.execute(
            "SELECT * FROM decisions ORDER BY created_at"
        ).fetchall()
        return [dict(r) for r in rows]

    def _export_memories(self) -> list[dict]:
        rows = self.sqlite.conn.execute(
            "SELECT * FROM memories ORDER BY created_at"
        ).fetchall()
        return [dict(r) for r in rows]

    def _export_entities(self) -> list[dict]:
        try:
            rows = self.sqlite.conn.execute(
                "SELECT * FROM entities ORDER BY created_at"
            ).fetchall()
            return [dict(r) for r in rows]
        except Exception:
            return []

    def _export_relations(self) -> list[dict]:
        try:
            rows = self.sqlite.conn.execute(
                "SELECT * FROM relations ORDER BY created_at"
            ).fetchall()
            return [dict(r) for r in rows]
        except Exception:
            return []

    def _export_fact_history(self) -> list[dict]:
        try:
            rows = self.sqlite.conn.execute(
                "SELECT * FROM fact_history ORDER BY changed_at"
            ).fetchall()
            return [dict(r) for r in rows]
        except Exception:
            return []
