"""Mergers & Acquisitions Synergy Hunter Workflow.

Reuses:
    - ``src.plugins.ce.mna.synergy_hunter.SynergyHunterAgent``
"""

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 SynergyWorkflow(BaseWorkflow):
    """Hunt for cross-company financial synergies.

    Useful for M&A integration and PE portfolio analysis.  Loads
    ledger/COA CSVs for each company and delegates to
    ``SynergyHunterAgent.hunt_shared_services()``.
    """

    name = "mna.synergy_hunter"
    category = "mna"
    description = "Analyze ledgers across companies to find consolidation opportunities"
    required_params = ["cluster_id", "company_files"]
    optional_params = {
        "efficiency_gain": 0.25,
    }

    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._hunt_synergies(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 Snowflake stored procedure that compares staged ledgers "
            "for shared-service consolidation opportunities",
        )

    @workflow_step("hunt_synergies", "Load company data and run synergy analysis")
    def _hunt_synergies(self, params: Dict[str, Any], ctx: Optional[SDKContext] = None):
        import pandas as pd
        from src.plugins.ce.mna.synergy_hunter import SynergyHunterAgent

        hunter = SynergyHunterAgent()

        company_data = {}
        for comp in params["company_files"]:
            name = comp.get("name")
            ledger_path = comp.get("ledger")
            coa_path = comp.get("coa")

            if name and ledger_path and coa_path:
                df_ledger = pd.read_csv(ledger_path)
                df_coa = pd.read_csv(coa_path)
                company_data[name] = {"ledger": df_ledger, "coa": df_coa}

        return hunter.hunt_shared_services(
            cluster_id=params["cluster_id"],
            company_data=company_data,
            efficiency_gain=params["efficiency_gain"],
        )
