# import json
# import logging
# from typing import Any, Dict, List, Optional, Tuple

# from pydantic import BaseModel

# from dhisana.utils.generate_structured_output_internal import get_structured_output_internal
# from dhisana.utils.workflow_code_model import WorkflowPythonCode

# # Example imports: adapt paths to your actual modules
# from dhisana.utils.generate_leads import generate_leads
# from dhisana.utils.qualify_leads import qualify_leads
# from dhisana.utils.compose_cadence import generate_campaign_cadence_workflow_and_execute

# # Initialize logger
# logging.basicConfig(level=logging.INFO)
# logger = logging.getLogger(__name__)


# class ThreeStepWorkflow(BaseModel):
#     """
#     Pydantic model representing the three-step workflow generated by LLM.
#     """
#     step_1_fetch_the_list: str
#     step_2_qualify_the_leads: str
#     step_3_execute_campaign_cadence: str


# async def generate_three_step_workflow(
#     english_description: str,
#     tool_config: Optional[List[Dict[str, Any]]] = None,
# ) -> Tuple[Dict[str, Any], str]:
#     """
#     Given a input, Split them into 3 Steps:
#       1) Step1: Describe how to fetch List of Leads with Sales Navigator.
#       2) How to qualify the leads (in plain English).
#       3) How to execute the LinkedIn/email campaign cadence.

#     Returns:
#         A tuple of:
#          - A dictionary matching the ThreeStepWorkflow model:
#             {
#                 "step_1_fetch_the_list": ...,
#                 "step_2_qualify_the_leads": ...,
#                 "step_3_execute_campaign_cadence": ...
#             }
#          - A string representing status, "SUCCESS" or "ERROR".
#     """
#     # A robust system prompt describing the required JSON structure
#     user_prompt = f"""
#     You are a helpful assistant. Please analyze the user's English description and produce a JSON object with 
#     three fields: step_1_fetch_the_list, step_2_qualify_the_leads, step_3_execute_campaign_cadence.

#     The user wants a 3-step workflow:
#       1) Step 1: Describe how to fetch the list of leads with LinkedIn sales navigator. If user has provided sales navigator URL include it in the instructions. 
#       2) Step 2: Describe How to qualify the leads. Extract how user has specified lead qualification and set it here.
#       3) Step 3: Describe How to enage the users execute the campaign cadence. Summarize how the user wants to engage leads on LinkedIn, email, or both (cadence rules, templates, etc.).
         
#     Output MUST be valid JSON, for example:
#     {{
#       "step_1_fetch_the_list": "How to fetch leads from Sales Navigator. Include sales navigator URL if provided.",
#       "step_2_qualify_the_leads": "Lead qualification instructions...",
#       "step_3_execute_campaign_cadence": "Instruction on how to engage the user..."
#     }}

#     Double-check that you produce valid JSON with exactly these three keys.

#     -- The user provided description is below --
#     {english_description}
#     """

#     # Use get_structured_output_internal to parse LLM output into ThreeStepWorkflow
#     response_obj, status = await get_structured_output_internal(
#         user_prompt,
#         ThreeStepWorkflow,
#         tool_config=tool_config
#     )

#     if status != "SUCCESS":
#         # Return a simple error response
#         return {"error": "Failed to generate three-step workflow."}, "ERROR"

#     # Convert the Pydantic model to a dictionary for easy usage
#     return response_obj.model_dump(), status


# async def generate_three_step_workflow_execute(
#     user_query: str,
#     input_leads_list: List[Dict[str, Any]],
#     tool_config: Optional[List[Dict[str, Any]]] = None
# ) -> str:
#     """
#     1. Generates a three-step workflow from the user query.
#     2. Executes:
#        - Step 1: Fetch leads from either Sales Navigator or a provided input list.
#        - Step 2: Qualify leads (Smart List).
#        - Step 3: Execute a LinkedIn/email cadence (Campaign Cadence).
#     3. Returns a JSON string describing success or error, including final leads if relevant.
#     """

#     try:
#         # Generate the 3-step instructions
#         three_step_response, status = await generate_three_step_workflow(
#             user_query,
#             tool_config=tool_config
#         )
#         if status != "SUCCESS":
#             return json.dumps({
#                 "status": "ERROR",
#                 "error": three_step_response.get("error", "Failed to generate three-step workflow.")
#             })

#         # Extract the step instructions
#         step_1_instructions = three_step_response.get("step_1_fetch_the_list", "")
#         step_2_instructions = three_step_response.get("step_2_qualify_the_leads", "")
#         step_3_instructions = three_step_response.get("step_3_execute_campaign_cadence", "")

#         # ==============================
#         # Step 1: Fetch leads
#         # ==============================
#         leads_list: List[Dict[str, Any]] = []
#         step_1_status = "SUCCESS"
#         if step_1_instructions == "use_input_file":
#             # We rely on the leads passed in as input
#             leads_list = input_leads_list
#             logger.info("Using leads from input file (already provided).")
#         else:
#             # We interpret step_1_instructions as a user query for sales nav
#             logger.info("Generating leads from sales nav instructions: %s", step_1_instructions)
#             result_str = await generate_leads(
#                 user_query=step_1_instructions,
#                 tool_config=tool_config
#             )
#             # Parse the JSON result to extract leads
#             try:
#                 result_json = json.loads(result_str)
#             except json.JSONDecodeError as e:
#                 logger.exception("Failed to parse Step 1 JSON output.")
#                 return json.dumps({
#                     "status": "ERROR",
#                     "error": f"Failed to parse Step 1 output as JSON: {e}"
#                 })

#             step_1_status = result_json.get("status", "ERROR")
#             if step_1_status != "SUCCESS":
#                 # Return early if step 1 fails
#                 return json.dumps({
#                     "status": "ERROR",
#                     "step": "step_1_fetch_the_list",
#                     "error": result_json.get("error", "Failed to fetch leads in step 1.")
#                 })

#             leads_list = result_json.get("leads", [])
#             logger.info("Step 1 completed with %d leads", len(leads_list))

#         # ==============================
#         # Step 2: Qualify leads
#         # ==============================
#         step_2_status = "SUCCESS"
#         if step_2_instructions:
#             logger.info("Executing smart list creation with instructions: %s", step_2_instructions)
#             try:
#                 # generate_smart_list_creation_code_and_execute typically returns JSON:
#                 # { "status": "SUCCESS", "qualified_leads": [...] }
#                 result_str = await qualify_leads(
#                     user_query=step_2_instructions,
#                     input_leads_list=leads_list,
#                     tool_config=tool_config
#                 )
#                 result_json = json.loads(result_str)
#                 step_2_status = result_json.get("status", "ERROR")
#                 if step_2_status != "SUCCESS":
#                     return json.dumps({
#                         "status": step_2_status,
#                         "step": "step_2_qualify_the_leads",
#                         "error": result_json.get("error", "Failed to qualify leads in step 2."),
#                         "leads_before_qualification": len(leads_list)
#                     })
#                 leads_list = result_json.get("qualified_leads", [])
#                 logger.info("Step 2 completed with %d leads after qualification", len(leads_list))
#             except Exception as exc:
#                 logger.exception("Exception during Step 2 (smart list).")
#                 return json.dumps({
#                     "status": "ERROR",
#                     "step": "step_2_qualify_the_leads",
#                     "error": str(exc)
#                 })

#         # ==============================
#         # Step 3: Execute campaign cadence
#         # ==============================
#         step_3_status = "SUCCESS"
#         if step_3_instructions:
#             logger.info("Executing campaign cadence with instructions: %s", step_3_instructions)
#             try:
#                 # generate_campaign_cadence_workflow_and_execute might return JSON:
#                 # { "status": "SUCCESS", "result": "Campaign done" } or similar
#                 result_str = await generate_campaign_cadence_workflow_and_execute(
#                     instructions=step_3_instructions,
#                     input_leads=leads_list,
#                     tool_config=tool_config
#                 )
#                 result_json = json.loads(result_str)
#                 step_3_status = result_json.get("status", "ERROR")
#                 if step_3_status != "SUCCESS":
#                     return json.dumps({
#                         "status": step_3_status,
#                         "step": "step_3_execute_campaign_cadence",
#                         "error": result_json.get("error", "Failed to run campaign in step 3.")
#                     })
#                 logger.info("Step 3 completed successfully.")
#             except Exception as exc:
#                 logger.exception("Exception during Step 3 (campaign cadence).")
#                 return json.dumps({
#                     "status": "ERROR",
#                     "step": "step_3_execute_campaign_cadence",
#                     "error": str(exc)
#                 })

#         # If all steps succeed, return final leads
#         return json.dumps({
#             "status": "SUCCESS",
#             "steps": {
#                 "step_1_status": step_1_status,
#                 "step_2_status": step_2_status,
#                 "step_3_status": step_3_status
#             },
#             "final_leads_count": len(leads_list),
#             "leads_list": leads_list
#         })

#     except Exception as e:
#         logger.exception("Exception in generate_three_step_workflow_execute.")
#         return json.dumps({"status": "ERROR", "error": str(e)})
