from __future__ import annotations

from typing import Generator

from pydantic import BaseModel

from ..graph_builder import GraphBuilder, ProgressInfo
from ..graph_db_instance_manager import EditorWebAppDbInstance
from ..models import GraphId
from ..store.graph_metadata_store import GraphMetadataStore


class Params(BaseModel):
    graph_id: GraphId


def reset_graph(store: GraphMetadataStore, params: Params) -> Generator[ProgressInfo, None, None]:
    """
    Raises:
        GraphDoesNotExistError
        GraphMetadataStoreError
        GraphDBWriteInProgressError
        RuntimeError
    """
    graph_id = params.graph_id

    graph_metadata = store.get(graph_id)

    with EditorWebAppDbInstance(graph_id, readonly=False) as local_db_instance:
        if local_db_instance.exists():
            local_db_instance.destroy()

        with GraphBuilder(local_db_instance) as builder:
            for progress in builder.insert_all(graph_metadata, track_progress=True):
                yield progress
