import os

def get_gcode_metadata(filepath):
    metadata = {
        'print_time': '-',
        'first_layer_time': '-',
        'filament_used': '-'
    }
    if not os.path.exists(filepath):
        return metadata
        
    try:
        # Read the last few KB to find estimated time and filament used
        with open(filepath, 'rb') as f:
            f.seek(0, 2)
            file_size = f.tell()
            chunk_size = min(65536, file_size)  # read last 64KB
            f.seek(file_size - chunk_size)
            chunk = f.read().decode('utf-8', errors='ignore')
            
            lines = chunk.splitlines()
            for line in reversed(lines):
                if line.startswith('; estimated printing time (normal mode) ='):
                    metadata['print_time'] = line.split('=')[1].strip()
                elif line.startswith('; estimated first layer printing time (normal mode) ='):
                    metadata['first_layer_time'] = line.split('=')[1].strip()
                elif line.startswith('; filament used [mm] ='):
                    metadata['filament_used'] = line.split('=')[1].strip()
    except Exception:
        pass
        
    return metadata
