
import os
import json
import pandas as pd
from datetime import datetime
import re

def create_timeline_from_session(session_path: str) -> pd.DataFrame:
    """
    Parses a debug session summary to find and process all variable dump files,
    returning the data as a time-sorted Pandas DataFrame.

    Args:
        session_path: The absolute path to the directory containing the session dumps.

    Returns:
        A Pandas DataFrame with 'timestamp', 'variable_name', and 'value' columns.
        Returns an empty DataFrame if the summary file is not found or is invalid.
    """
    if not os.path.isdir(session_path):
        return pd.DataFrame()

    summary_file = None
    for filename in os.listdir(session_path):
        if 'summary' in filename and filename.endswith('.json'):
            summary_file = os.path.join(session_path, filename)
            break

    if not summary_file:
        return pd.DataFrame()

    try:
        with open(summary_file, 'r', encoding='utf-8') as f:
            summary_data = json.load(f)
    except (IOError, json.JSONDecodeError):
        return pd.DataFrame()

    records = []
    # The key 'files_produced_detailed' holds the list of all dump events
    for dump_info in summary_data.get('files_produced_detailed', []):
        variable_name = dump_info.get('variable')
        file_produced = dump_info.get('file_produced')
        full_path = dump_info.get('full_path')

        if not all([variable_name, file_produced, full_path]):
            continue

        # Extract high-precision timestamp from the filename
        # e.g., ..._20250925_085026_750.json -> 20250925085026750
        match = re.search(r'_(\d{8}_\d{6}_\d{3})\.', file_produced)
        if not match:
            continue
        
        timestamp_str = match.group(1).replace('_', '')
        
        try:
            # The format string includes date, time, and milliseconds
            timestamp = datetime.strptime(timestamp_str, '%Y%m%d%H%M%S%f')
        except ValueError:
            continue

        # Read the individual dump file to get the variable's value
        try:
            _, file_extension = os.path.splitext(full_path)
            value_str = ""

            with open(full_path, 'r', encoding='utf-8') as f_dump:
                if file_extension.lower() == '.json':
                    content = json.load(f_dump)
                    # The actual data is in the 'data' key, store it as a JSON string
                    value_str = json.dumps(content.get('data', {}))
                else: # Assume CSV or other text-based format
                    value_str = f_dump.read()
            
            records.append({
                'timestamp': timestamp,
                'variable_name': variable_name,
                'value': value_str
            })

        except (IOError, json.JSONDecodeError):
            # Log or handle error for individual file read
            continue
            
    if not records:
        return pd.DataFrame()

    df = pd.DataFrame(records)
    # Sort by timestamp to create the correct timeline
    df.sort_values(by='timestamp', inplace=True)
    df.reset_index(drop=True, inplace=True)
    
    return df
