"""Graph & vector training workflow — discover, profile, detect, index, embed.

Wraps the 8-phase ``scripts/train_graph_vectors.py`` pipeline as an SDK
workflow so AI agents can trigger training via MCP tools.

Reuses:
    - ``scripts.train_graph_vectors.TrainingPipeline``
    - ``databridge.triage.scan_and_classify``
    - ``databridge.profiler.profile_data``
    - ``databridge.erp_detect.detect_erp_batch``
    - ``databridge.detection.detect_grounded``
    - ``src.codex_graphrag.core.build_index``
    - ``src.graphrag.embedding_provider.get_embedding_provider``
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from databridge_core.sdk.core.context import SDKContext
from databridge_core.sdk.core.types import CompiledArtifact, Result, Status, StepOutcome
from databridge_core.sdk.workflows.base import BaseWorkflow
from databridge_core.sdk.workflows.result import WorkflowResult
from databridge_core.sdk.workflows.step import workflow_step


class GraphVectorTrainingWorkflow(BaseWorkflow):
    """Run the 8-phase graph & vector training pipeline.

    Discovers ~20K data assets across 6 repositories, profiles them,
    detects ERP systems and anomalies, generates Codex GraphRAG sidecars,
    builds graph indexes, and embeds into vector stores.

    Reuses:
        - ``scripts.train_graph_vectors.TrainingPipeline``
    """

    name = "training.graph_vectors"
    category = "training"
    description = "Train graph indexes and vector embeddings from data repositories"
    required_params = []
    optional_params = {
        "phases": "0,1,2,3,4,5,6,7",
        "batch_size": 200,
        "sample_rate": 1.0,
        "skip_vectors": False,
        "dry_run": False,
    }

    def validate(self, params: Dict[str, Any]) -> Dict[str, Any]:
        return self._apply_defaults(params)

    def execute(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> Result:
        steps = [self._run_pipeline(params, ctx)]
        return WorkflowResult.from_steps(self.name, steps)

    def compile_to_snowflake(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> List[CompiledArtifact]:
        from databridge_core.sdk.core.exceptions import NotImplementedStubError

        raise NotImplementedStubError(
            self.name,
            "compile_to_snowflake",
            "Training pipeline runs locally — no Snowflake DDL compilation.",
        )

    @workflow_step("run_pipeline", "Execute the training pipeline phases")
    def _run_pipeline(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ):
        import sys
        from pathlib import Path

        repo_root = Path(__file__).resolve().parents[3]
        sys.path.insert(0, str(repo_root))

        from scripts.train_graph_vectors import TrainingConfig, TrainingPipeline

        phases_raw = params.get("phases", "0,1,2,3,4,5,6,7")
        if isinstance(phases_raw, str):
            phases = [int(x.strip()) for x in phases_raw.split(",")]
        else:
            phases = list(phases_raw)

        config = TrainingConfig(
            phases=phases,
            dry_run=params.get("dry_run", False),
            batch_size=params.get("batch_size", 200),
            sample_rate=params.get("sample_rate", 1.0),
            skip_vectors=params.get("skip_vectors", False),
        )

        pipeline = TrainingPipeline(config)
        result = pipeline.run()

        return {
            "phases_run": len(pipeline.results),
            "total_files": sum(r.files_processed for r in pipeline.results),
            "total_errors": sum(r.errors for r in pipeline.results),
            "phase_summaries": [
                {
                    "phase": r.phase,
                    "name": r.name,
                    "files_processed": r.files_processed,
                    "errors": r.errors,
                    "elapsed_seconds": round(r.elapsed_seconds, 1),
                }
                for r in pipeline.results
            ],
        }
