import db
import slicer_utils
import preview_utils
import config
import os
from typing import List

def process_order_slicing(order_id: int):
    """
    Background task to compute accurate print time and filament usage for all files in an order.
    """
    files = db.execute_query("SELECT id, file_path FROM order_files WHERE order_id = %s", (order_id,))
    if not files:
        return

    for f in files:
        file_path = f['file_path']
        if not os.path.exists(file_path):
            continue
            
        file_ext = os.path.splitext(file_path)[1].lower()
        if file_ext == '.stl':
            result = slicer_utils.slice_model(file_path)
            if result and result.get('success'):
                db.execute_commit(
                    "UPDATE order_files SET print_time = %s, filament_g = %s, dimensions = %s WHERE id = %s",
                    (result.get('print_time_str'), result.get('filament_g'), result.get('dimensions'), f['id'])
                )

def process_single_file_async(file_id: int):
    """
    Background task to generate preview and slice a single file.
    (Updated to force module reload)
    """
    f = db.execute_query("SELECT id, order_id, file_path, filename FROM order_files WHERE id = %s", (file_id,))
    if not f:
        return
    
    f = f[0]
    file_path = os.path.join(config.BASE_DIR, f['file_path'])
    if not os.path.exists(file_path):
        return
        
    file_ext = os.path.splitext(file_path)[1].lower()
    if file_ext == '.stl':
        # 1. Generate Preview
        import uuid
        preview_filename = f"{uuid.uuid4()}.png"
        preview_path = os.path.join(config.PREVIEW_DIR, preview_filename)
        db_preview_path = f"uploads/previews/{preview_filename}"
        
        if preview_utils.generate_stl_preview(file_path, preview_path):
            db.execute_commit("UPDATE order_files SET preview_path = %s WHERE id = %s", (db_preview_path, file_id))

        # 2. Slice for print data
        result = slicer_utils.slice_model(file_path)
        if result and result.get('success'):
            db.execute_commit(
                "UPDATE order_files SET print_time = %s, filament_g = %s, dimensions = %s WHERE id = %s",
                (result.get('print_time_str'), result.get('filament_g'), result.get('dimensions'), file_id)
            )
            
    # Notify user/admin via WS if possible?
    # (Optional: global_manager.notify_order_update could be called here)

