import pandas as pd
import orjson
import os

def process_trigger_results(json_data):
    """
    Process the trigger results from the JSON data and write to Excel.
    
    Args:
        json_data (str): JSON string containing the trigger results
    """
    try:
        # Parse the JSON data
        data = orjson.loads(json_data)
        
        # Extract the output array from the data
        if isinstance(data, dict) and 'data' in data:
            output_data = orjson.loads(data['data'])
            if isinstance(output_data, dict) and 'output' in output_data:
                output_array = orjson.loads(output_data['output'])
            else:
                raise ValueError("Invalid data structure: 'output' not found in data")
        else:
            raise ValueError("Invalid data structure: 'data' not found in root")
        
        # Create a list to store the extracted fields
        results = []
        
        # Extract required fields from each item
        for item in output_array:
            result = {
                '需求钩子出现时间': item.get('需求钩子出现时间', ''),
                '需求详细query': item.get('需求详细query', ''),
                '需求钩子话术': item.get('需求钩子话术', '')
            }
            results.append(result)
        
        # Create DataFrame
        df = pd.DataFrame(results)
        
        # Write to Excel
        output_file = 'trigger_result.xlsx'
        df.to_excel(output_file, index=False)
        
        print(f"Successfully wrote {len(results)} records to {output_file}")
        
    except Exception as e:
        print(f"Error processing trigger results: {str(e)}")
        raise

def process_file(input_file):
    """
    Process a file containing JSON data and write results to Excel.
    
    Args:
        input_file (str): Path to the input file containing JSON data
    """
    try:
        # Read the input file
        with open(input_file, 'r', encoding='utf-8') as f:
            json_data = f.read()
        
        # Process the data
        process_trigger_results(json_data)
        
    except Exception as e:
        print(f"Error processing file {input_file}: {str(e)}")
        raise

if __name__ == '__main__':
    # Example usage
    input_file = 'trigger_response.json'  # Replace with your input file path
    if os.path.exists(input_file):
        process_file(input_file)
    else:
        print(f"Input file {input_file} not found") 