"""Architectural Integrity Scoring Workflow.

Reuses:
    - ``design_studio.core.ais_engine.AISEngine``
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from databridge_core.sdk.core.context import SDKContext
from databridge_core.sdk.core.exceptions import NotImplementedStubError
from databridge_core.sdk.core.types import CompiledArtifact, Result
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 ArchitecturalScoringWorkflow(BaseWorkflow):
    """Calculate the unified Architectural Integrity Score (AIS).

    Aggregates Logic (forensic), Design (aesthetic violations), and
    Synergy (M&A overlap) metrics into a single 0-100 score.
    Delegates to ``AISEngine.calculate_score()``.
    """

    name = "architect.ais_score"
    category = "architect"
    description = "Calculate unified organizational health score (0-100)"
    required_params = ["forensic_results", "design_violations"]
    optional_params = {
        "synergy_report": None,
    }

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

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

    def compile_to_snowflake(
        self, params: Dict[str, Any], ctx: Optional[SDKContext] = None
    ) -> List[CompiledArtifact]:
        raise NotImplementedStubError(
            self.name,
            "compile_to_snowflake",
            "Generate a Snowflake stored procedure that computes AIS from "
            "forensic results and design violation tables",
        )

    @workflow_step("calculate_ais", "Compute Architectural Integrity Score")
    def _calculate_ais(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        import dataclasses
        from design_studio.core.ais_engine import AISEngine

        engine = AISEngine()
        ais_result = engine.calculate_score(
            forensic_results=params["forensic_results"],
            design_violations=params["design_violations"],
            synergy_report=params.get("synergy_report"),
        )

        # Convert dataclass to dict if needed
        if dataclasses.is_dataclass(ais_result):
            return dataclasses.asdict(ais_result)
        return ais_result
