import asyncio
import json
from os import wait
from typing import Optional, List

from crewai.flow.flow import start, listen, and_
from flask import current_app
from pydantic import BaseModel, Field
from sqlalchemy.exc import SQLAlchemyError

from common.extensions import db
from common.models.user import Tenant
from common.models.interaction import Specialist
from eveai_chat_workers.outputs.globals.basic_types.list_item import ListItem
from eveai_chat_workers.specialists.crewai_base_specialist import CrewAIBaseSpecialistExecutor
from eveai_chat_workers.specialists.specialist_typing import SpecialistResult, SpecialistArguments
from eveai_chat_workers.outputs.traicie.competencies.competencies_v1_1 import Competencies
from eveai_chat_workers.specialists.crewai_base_classes import EveAICrewAICrew, EveAICrewAIFlow, EveAIFlowState
from common.services.interaction.specialist_services import SpecialistServices

NEW_SPECIALIST_TYPE = "TRAICIE_SELECTION_SPECIALIST"
NEW_SPECIALIST_TYPE_VERSION = "1.5"


class SpecialistExecutor(CrewAIBaseSpecialistExecutor):
    """
    type: TRAICIE_ROLE_DEFINITION_SPECIALIST
    type_version: 1.0
    Traicie Role Definition Specialist Executor class
    """

    def __init__(self, tenant_id, specialist_id, session_id, task_id, **kwargs):
        self.role_definition_crew = None

        super().__init__(tenant_id, specialist_id, session_id, task_id)

        # Load the Tenant & set language
        self.tenant = Tenant.query.get_or_404(tenant_id)

    @property
    def type(self) -> str:
        return "TRAICIE_ROLE_DEFINITION_SPECIALIST"

    @property
    def type_version(self) -> str:
        return "1.3"

    def _config_task_agents(self):
        self._add_task_agent("traicie_get_competencies_task", "traicie_hr_bp_agent")

    def _config_pydantic_outputs(self):
        self._add_pydantic_output("traicie_get_competencies_task", Competencies, "competencies")

    def _config_state_result_relations(self):
        self._add_state_result_relation("competencies")

    def _instantiate_specialist(self):
        verbose = self.tuning

        role_definition_agents = [self.traicie_hr_bp_agent]
        role_definition_tasks = [self.traicie_get_competencies_task]
        self.role_definition_crew = EveAICrewAICrew(
            self,
            "Role Definition Crew",
            agents=role_definition_agents,
            tasks=role_definition_tasks,
            verbose=verbose,
        )

        self.flow = RoleDefinitionFlow(
            self,
            self.role_definition_crew
        )

    def _config_state_result_relations(self):
        pass

    def execute(self, arguments: SpecialistArguments, formatted_context, citations) -> SpecialistResult:
        self.log_tuning("Traicie Role Definition Specialist execution started", {})

        flow_inputs = {
            "vacancy_text": arguments.vacancy_text,
            "role_name": arguments.role_name,
            'role_reference': arguments.role_reference,
        }

        flow_results = self.flow.kickoff(inputs=flow_inputs)

        results = RoleDefinitionSpecialistResult.create_for_type(self.type, self.type_version)

        self.create_selection_specialist(arguments, self.flow.state.competencies)

        self.log_tuning(f"Traicie Role Definition Specialist execution ended", {"Results": results.model_dump()})

        return results

    def create_selection_specialist(self, arguments: SpecialistArguments, competencies: List[ListItem]):
        """This method creates a new TRAICIE_SELECTION_SPECIALIST specialist with the given competencies."""
        current_app.logger.info(f"Creating selection with arguments: {arguments.model_dump()}")
        selection_comptencies = []
        for competency in competencies:
            selection_competency = {
                "title": competency.title,
                "description": competency.description,
                "assess": True,
                "is_knockout": False,
            }
            selection_comptencies.append(selection_competency)

        selection_config = {
            "name": arguments.specialist_name,
            "competencies": selection_comptencies,
            "tone_of_voice": "Professional & Neutral",
            "language_level": "Standard",
            "role_reference": arguments.role_reference,
            "make": arguments.make,
        }
        name = arguments.role_name
        if len(name) > 50:
            name = name[:47] + "..."

        new_specialist = Specialist(
            name=name,
            description=f"Specialist for {arguments.role_name} role",
            type=NEW_SPECIALIST_TYPE,
            type_version=NEW_SPECIALIST_TYPE_VERSION,
            tuning=False,
            configuration=selection_config,
        )
        try:
            db.session.add(new_specialist)
            db.session.commit()
        except SQLAlchemyError as e:
            db.session.rollback()
            current_app.logger.error(f"Error creating selection specialist: {str(e)}")
            raise e

        SpecialistServices.initialize_specialist(new_specialist.id, NEW_SPECIALIST_TYPE, NEW_SPECIALIST_TYPE_VERSION)




class RoleDefinitionSpecialistInput(BaseModel):
    role_name: str = Field(..., alias="role_name")
    role_reference: Optional[str] = Field(..., alias="role_reference")
    vacancy_text: Optional[str] = Field(None, alias="vacancy_text")


class RoleDefinitionSpecialistResult(SpecialistResult):
    competencies: Optional[List[ListItem]] = None


class RoleDefFlowState(EveAIFlowState):
    """Flow state for Traicie Role Definition specialist that automatically updates from task outputs"""
    input: Optional[RoleDefinitionSpecialistInput] = None
    competencies: Optional[List[ListItem]] = None


class RoleDefinitionFlow(EveAICrewAIFlow[RoleDefFlowState]):
    def __init__(self,
                 specialist_executor: CrewAIBaseSpecialistExecutor,
                 role_definitiion_crew: EveAICrewAICrew,
                 **kwargs):
        super().__init__(specialist_executor, "Traicie Role Definition Specialist Flow", **kwargs)
        self.specialist_executor = specialist_executor
        self.role_definition_crew = role_definitiion_crew
        self.exception_raised = False

    @start()
    def process_inputs(self):
        return ""

    @listen(process_inputs)
    async def execute_role_definition   (self):
        inputs = self.state.input.model_dump()
        try:
            crew_output = await self.role_definition_crew.kickoff_async(inputs=inputs)
            # Unfortunately, crew_output will only contain the output of the latest task.
            # As we will only take into account the flow state, we need to ensure both competencies and criteria
            # are copies to the flow state.
            update = {}
            for task in self.role_definition_crew.tasks:
                if task.name == "traicie_get_competencies_task":
                    # update["competencies"] = task.output.pydantic.competencies
                    self.state.competencies = task.output.pydantic.competencies
            # crew_output.pydantic = crew_output.pydantic.model_copy(update=update)
            return crew_output
        except Exception as e:
            current_app.logger.error(f"CREW execute_role_definition Kickoff Error: {str(e)}")
            self.exception_raised = True
            raise e

    async def kickoff_async(self, inputs=None):
        self.state.input = RoleDefinitionSpecialistInput.model_validate(inputs)
        result = await super().kickoff_async(inputs)
        return self.state
