# process_data.py

import time
from config import API_URL, INPUT_EXCEL_FILE, OUTPUT_EXCEL_FILE, OUTPUT_HEADERS, FORMATTED_RESPONSES_COUNT
from utils import load_excel, save_excel, create_output_workbook
from utils.unpack_data import unpack_input_data  # Import the new unpack function
from utils.api_client import send_api_request
#pands data format


def process_rows():
    # Load input workbook
    workbook = load_excel(INPUT_EXCEL_FILE)
    sheet = workbook.active

    # Generate dynamic output headers
    output_headers = OUTPUT_HEADERS + [
        f"Formatted Response{i + 1}" for i in range(FORMATTED_RESPONSES_COUNT)
    ] + [
        f"Response Time{i + 1} (seconds)" for i in range(FORMATTED_RESPONSES_COUNT)
    ]

    # Create output workbook
    output_workbook = create_output_workbook(output_headers)
    output_sheet = output_workbook.active

    for row_index, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
        if all(cell is None for cell in row):
            print(f"Skipping empty row {row_index}")
            continue

        # Map input columns to header keys dynamically
        input_data = {header: row[i] for i, header in enumerate(OUTPUT_HEADERS)}

        # Check if all required fields are present
        if any(value is None for value in input_data.values()):
            print(f"Skipping row {row_index}: Missing required data")
            continue

        print(f"Processing row {row_index}")

        # Unpack input data and prepare the payload
        payload = unpack_input_data(input_data)

        responses = []
        response_times = []

        for _ in range(FORMATTED_RESPONSES_COUNT):
            try:
                response, response_time = send_api_request(API_URL, payload)

                # Check if the response is an actual response object and contains status_code
                if isinstance(response, dict):  # The response is likely the JSON data
                    formatted_response = "Response:\n"
                    for key, value in response.items():
                        if isinstance(value, str) and "\n" in value:
                            formatted_response += f"{key.capitalize()}:\n{value.strip()}\n"
                        else:
                            formatted_response += f"{key.capitalize()}: {value}\n"
                    formatted_response += "-" * 50
                    responses.append(formatted_response)
                else:
                    # If the response doesn't contain JSON, handle error (may need to add a check here)
                    error_response = f"Error: Invalid response format received\n"
                    responses.append(error_response)

                response_times.append(response_time)
            except Exception as e:
                # Handle unexpected exceptions
                error_message = f"Exception occurred: {str(e)}"
                responses.append(error_message)
                response_times.append(0)

            time.sleep(1)

        # Append data to the output sheet
        output_row = list(input_data.values()) + [
            responses[i] if i < len(responses) else "N/A" for i in range(FORMATTED_RESPONSES_COUNT)
        ] + [
            response_times[i] if i < len(response_times) else 0 for i in range(FORMATTED_RESPONSES_COUNT)
        ]

        output_sheet.append(output_row)

    # Save the output workbook
    save_excel(output_workbook, OUTPUT_EXCEL_FILE)
    print(f"Responses saved in {OUTPUT_EXCEL_FILE}")