<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Python_extractor {

    protected $ci;
    protected $python_script;
    protected $python_path;

    public function __construct() {
        $this->ci =& get_instance();
        $this->python_script = $this->ci->config->item('python_script');
        $this->python_path = $this->ci->config->item('python_path');
    }

    public function process_pdf($record) {
        $pdf_path = FCPATH . 'assets/uploads/tmp/' . $record->filename;
        
        if (!file_exists($pdf_path)) {
            return array(
                'status' => false,
                'error' => 'PDF file not found'
            );
        }

        if (!file_exists($this->python_script)) {
            return array(
                'status' => false,
                'error' => 'Python script not found'
            );
        }

        // Prepare command
        $command = $this->python_path . ' "' . $this->python_script . '" "' . $pdf_path . '" "' . $record->id . '" "' . $record->original_name . '" 2>&1';
        
        // Execute Python script
        $output = shell_exec($command);
        
        // Parse output
        return $this->parse_python_output($output, $record->id);
    }

    private function parse_python_output($output, $record_id) {
        // Look for JSON result in output
        $pattern = '/\{.*\}/s';
        if (preg_match($pattern, $output, $matches)) {
            $result = json_decode($matches[0], true);
            
            if (json_last_error() === JSON_ERROR_NONE) {
                return array(
                    'status' => true,
                    'data' => $result
                );
            }
        }

        return array(
            'status' => false,
            'error' => 'Python script execution failed: ' . $output
        );
    }

    public function check_python_environment() {
        $command = $this->python_path . ' --version 2>&1';
        $output = shell_exec($command);
        
        return !empty($output);
    }
}