<?php

namespace App\Services;

use App\Models\Product;
use App\Models\WorkOrder;
use App\Models\User;
use App\Models\Machine;
use App\Models\Inventory;
use App\Models\BomItem;
use App\Models\StockMovement;
use App\Mail\AssistantNotification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;

class AssistantExpertService
{
    /**
     * Process a natural language message via the Python AI Engine.
     */
    public function ask($message)
    {
        $pythonPath = 'python'; // Ensure python is in the PATH
        $scriptPath = base_path('ai/ai_engine.py');
        $command = escapeshellcmd("$pythonPath \"$scriptPath\" \"$message\"");
        
        $output = shell_exec($command);
        $result = json_decode($output, true);

        if (isset($result['action']) && $result['action'] == 'send_email') {
            try {
                Mail::to($result['recipient'])->send(new AssistantNotification($result['subject'], $result['body']));
                return $result['confirmation'] ?? "Email sent successfully to {$result['recipient']}.";
            } catch (\Exception $e) {
                return "I prepared the email, but encountered an error sending it: " . $e->getMessage();
            }
        }

        if (isset($result['response'])) {
            return $result['response'];
        }

        // Fallback to a better message if Python fails
        return "I'm currently indexing your latest production data. Please ask me about stock, consumption, or user actions in a few moments!";
    }
}
