from fastapi import APIRouter, HTTPException, Body
from pydantic import BaseModel
from typing import Optional
from user_journey_service.crew import UserJourney 
from ..models.schemas import QueryRequest
from ..utils.hashing import HashGenerator
import os
from user_journey_service.services.user_journey_service import MicrolearningService
from user_journey_service.services.content_creation_service import ContentCreationService
from user_journey_service.services.defaults_service import DefaultEstimator
from user_journey_service.services.summary_creation_service import SummaryCreationService
from user_journey_service.services.evaluation_service import EvaluationService


###/home/azureuser/microlearn/backend/user_journey_with_openai/agentic_workflow/src/user_journey_service/services/user_interaction_service.py
router = APIRouter()

def get_microlearning_service(input_data):
    service = MicrolearningService(input_data)
    return service
  
def get_content_creation_service(input_data):
    service = ContentCreationService(input_data)
    return service

def get_evaluation_service(input_data):
    service = EvaluationService(input_data)
    return service

def get_defaults_service(input_data):
    service = DefaultEstimator(input_data)
    return service
    
def get_summary_creation_service(input_data):
    service = SummaryCreationService(input_data)
    return service

@router.post("/run-crew")
def run_crew(input_data: QueryRequest):
    """
    Run AI development crew with provided input.
    """

    try:
        # user_journeyservice = get_microlearning_service(input_data)
        # response = user_journeyservice.run_journey()
        # print(f"the response from first satge is : {response}")
        # if response["message"] == "Invalid topic.":
        #     return response
        # content_creation_service = get_content_creation_service(input_data)
        # response = content_creation_service.run_content_creation()
        # print(response)
        run_evaluation = get_user_interaction_service(input_data)
        response = run_evaluation.run()
        # run_summary = get_summary_creation_service(input_data)
        # print("Service initialised..")
        # response = run_summary.run()
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")

@router.post("/run-defaults")      #### without async
def run_crew(input_data: QueryRequest):
    """
    Run AI development crew with provided input.
    """

    service = get_defaults_service(input_data)
    response = service.run()
    if response["status"] == "failed":
        response = service.run()
    return response

# @router.post("/run-defaults")         #### for async
# async def run_crew(input_data: QueryRequest):
#     """
#     Run AI development crew with provided input.
#     """

#     service = get_defaults_service(input_data)
#     response = await service.run()
#     return response
    

@router.post("/run-journey")
def run_crew(input_data: QueryRequest):
    """
    Run AI development crew with provided input.
    """

    try:
        user_journeyservice = get_microlearning_service(input_data)
        response = user_journeyservice.run_journey()
        print(f"the response from first satge is : {response}")
        if response["message"] == "Invalid topic.":
            return response
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")


@router.post("/run-summary")
def run_crew(input_data: QueryRequest):
    """
    Run AI development crew with provided input.
    """

    try:
        run_summary = get_summary_creation_service(input_data)
        print("Service initialised..")
        response = run_summary.run()
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")


@router.post("/run-contentcreation")
def run_crew(input_data: QueryRequest):
    """
    Run AI development crew with provided input.
    """

    try:
        
        service = get_content_creation_service(input_data)
        response = service.run_content_creation()
        print(response)
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")



@router.post("/session-list")
def run_crew(input_data: QueryRequest):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    print(f"the input data type is : {type(input_data)}")
    try:
       
        service = get_evaluation_service(input_data)
        # files = service.generate_stage_file_mapping()
        files = service.update_parsed_course_content()
        return files
        # return match,missing
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")


@router.post("/session-content")
def run_crew(input_data: QueryRequest = Body(...),
    file: dict = Body(...)):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    print(f"the input data type is : {type(input_data)}")
    try:
       
        service = get_evaluation_service(input_data)
        files = service.display_content(file)
        return files
        # return match,missing
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")

@router.post("/session-qn-list")
def run_crew(input_data: QueryRequest = Body(...),
    file: dict = Body(...)):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    print(f"the input data type is : {type(input_data)}")
    try:
       
        service = get_evaluation_service(input_data)
        files = service.list_qns(file)
        return files
        # return match,missing
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")

@router.post("/question")
def run_crew(input_data: QueryRequest = Body(...),
    file: str = Body(...)):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    print(f"the input data type is : {type(input_data)}")
    try:
       
        service = get_evaluation_service(input_data)
        files = service.display_question(file)
        return files
        # return match,missing
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")


@router.post("/qn-evaluation")
def run_crew(file: str = Body(...),input_data: QueryRequest = Body(...)):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    print(f"the input data type is : {type(input_data)}")
    try:
       
        service = get_evaluation_service(input_data)
        feedback = service.evaluate_individual_qn(file)
        return feedback
        # return match,missing
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")




@router.post("/evaluate_answer")    ### extra added endpoint for accepting qn and answer from user, added on Nov 13th 2025
def run_crew(question: str=Body(...), answer: str=Body(...), input_data: QueryRequest = Body(...)):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    print(f"the input data type is : {type(input_data)}")
    try:
       
        service = get_evaluation_service(input_data)
        feedback = service.evaluate_individual_qn_ans_pair(question,answer)
        return feedback
        # return match,missing
    
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")

@router.post("/run-evaluation")
def run_crew(input_data: QueryRequest = Body(...),
    file: dict = Body(...)):
    """
    Run AI development crew with provided input.
    """
    print(f"the input data is : {input_data}")
    try:
        
        service = get_evaluation_service(input_data)
        print(file)
        service.play_content(file)
        service.run_evaluation(file)
        # print(response)
        # return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
