import logging
from contextlib import contextmanager
from pathlib import Path
import pickle
from typing import Optional

import appdirs

from .settings import APP_NAME

logger = logging.getLogger(__name__)

config_dir = appdirs.user_config_dir(appname=APP_NAME)
logger.debug(f"Using config directory: {config_dir}")
Path(config_dir).mkdir(parents=True, exist_ok=True)
workflows_store_path = Path(config_dir) / "workflow_executions.pkl"


class WorkflowsStore:
    def __init__(self, store_path: Path = workflows_store_path):
        self.store_path = store_path
        self.store_path.parent.mkdir(parents=True, exist_ok=True)
        if not self.store_path.exists():
            self._write_store({})

    def _read_store(self) -> dict:
        with open(self.store_path, "rb") as f:
            return pickle.load(f)

    def _write_store(self, data: dict) -> None:
        with open(self.store_path, "wb") as f:
            pickle.dump(data, f)

    def get_workflow(self, workflow_id: str) -> Optional[dict]:
        store = self._read_store()
        return store.get(workflow_id)

    def save_workflow(self, workflow) -> None:
        store = self._read_store()
        store[workflow.workflow_id] = workflow
        self._write_store(store)

    @contextmanager
    def edit_workflow(self, workflow_id: str):
        """Context manager for editing and auto-saving workflows."""
        workflow = self.get_workflow(workflow_id)
        if not workflow:
            raise ValueError(f"Unknown workflow_id: {workflow_id}")

        try:
            yield workflow
        finally:
            # Always save, even if exception occurred
            self.save_workflow(workflow)


workflow_store = WorkflowsStore()
