"""Hierarchy Builder specialist agent.

Responsible for constructing hierarchy projects from discovered table
groupings and metadata.
"""

from __future__ import annotations

import json
import logging
from typing import Any, Dict

from .base_agent import BaseDataBridgeAgent
from .state_schema import WorkflowState
from .databridge_tools import tool_create_hierarchy, tool_group_tables

logger = logging.getLogger(__name__)


class HierarchyAgent(BaseDataBridgeAgent):
    """Specialist agent for hierarchy construction."""

    name = "hierarchy_agent"
    description = "Builds hierarchies from discovered table groupings and metadata"
    phase_name = "hierarchy"

    def __init__(self, **kwargs):
        super().__init__(
            tools=[tool_create_hierarchy, tool_group_tables],
            system_prompt=(
                "You are the Hierarchy Builder agent for DataBridge AI. "
                "Your job is to analyse table groupings and create hierarchy "
                "projects that organise data dimensions for downstream "
                "warehousing and analytics."
            ),
            **kwargs,
        )

    async def run(self, state: WorkflowState) -> WorkflowState:
        """Build hierarchy from table groups discovered in earlier phases."""
        ctx = dict(state.get("context", {}))
        groups = ctx.get("group_tables", {}).get("groups", {})

        if not groups:
            result = {"status": "placeholder", "note": "No groups available for hierarchy"}
            return self._update_context(state, self.phase_name, result)

        # Build hierarchy from group structure
        hierarchy_levels = []
        for group_name, tables in groups.items():
            hierarchy_levels.append({
                "name": group_name,
                "depth": 0,
                "tables": tables if isinstance(tables, list) else [tables],
            })

        result = {
            "status": "completed",
            "groups_processed": len(groups),
            "hierarchy_levels": len(hierarchy_levels),
            "levels": hierarchy_levels,
        }

        return self._update_context(state, self.phase_name, result)
