<?php

namespace App\Http\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class APIService
{
    private $clinicalBaseUrl = 'http://45.159.112.210:8000';
    private $imageBaseUrl = 'http://45.159.112.210:8001';

    /**
     * Health check for clinical API
     */
    public function checkClinicalAPI()
    {
        try {
            $response = Http::timeout(10)->get($this->clinicalBaseUrl . '/health');
            return [
                'success' => $response->successful(),
                'data' => $response->json(),
                'status' => $response->status()
            ];
        } catch (\Exception $e) {
            Log::error('Clinical API health check failed: ' . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Health check for image API
     */
    public function checkImageAPI()
    {
        try {
            $response = Http::timeout(10)->get($this->imageBaseUrl . '/image/health');
            return [
                'success' => $response->successful(),
                'data' => $response->json(),
                'status' => $response->status()
            ];
        } catch (\Exception $e) {
            Log::error('Image API health check failed: ' . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Send clinical data to API
     */
    public function sendClinicalData(array $features)
    {
        try {
            $response = Http::timeout(30)
                ->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                ])
                ->post($this->clinicalBaseUrl . '/predict', [
                    'features' => $features
                ]);

            return [
                'success' => $response->successful(),
                'data' => $response->json(),
                'status' => $response->status(),
                'raw_response' => $response->body()
            ];
        } catch (\Exception $e) {
            Log::error('Clinical API prediction failed: ' . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

    /**
     * Send image to API for prediction
     */
    public function sendImage($imageFile, $fileName = null)
    {
        try {
            $response = Http::timeout(60)
                ->withHeaders([
                    'Accept' => 'application/json',
                ])
                ->attach('file', file_get_contents($imageFile), $fileName ?? 'fundus_image.jpg')
                ->post($this->imageBaseUrl . '/image/predict');

            return [
                'success' => $response->successful(),
                'data' => $response->json(),
                'status' => $response->status(),
                'raw_response' => $response->body()
            ];
        } catch (\Exception $e) {
            Log::error('Image API prediction failed: ' . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }

        public function mapFormToFeatures(array $formData)
    {
        // Define all 115 required features with default value 0
        $features = [
            'Diabetes' => 0,
            'FBS' => 0,
            'CHOL' => 0,
            'HDL' => 0,
            'TG' => 0,
            'DiabetesControl' => 0,
            'Diabetes.RAAB.NCD' => 0,
            'C2' => 0,
            'C1' => 0,
            'E1' => 0,
            'E5' => 0,
            'E4' => 0,
            'E6' => 0,
            'E2' => 0,
            'E3' => 0,
            'E8' => 0,
            'F1' => 0,
            'F1_harrooz' => 0,
            'F1_darmian' => 0,
            'F1_darmianN' => 0,
            'F2' => 0,
            'F2_harrooz' => 0,
            'F2_darmian' => 0,
            'F2_darmianN' => 0,
            'F3' => 0,
            'F3_harrooz' => 0,
            'F3_darmian' => 0,
            'F3_darmianN' => 0,
            'F6' => 0,
            'F7' => 0,
            'F8' => 0,
            'F9' => 0,
            'F10' => 0,
            'F11' => 0,
            'G1' => 0,
            'G1_duration' => 0,
            'G2' => 0,
            'G2_duration' => 0,
            'K1' => 0,
            'K2' => 0,
            'K3' => 0,
            'K4' => 0,
            'K5' => 0,
            'H1_month' => 0,
            'H1_year' => 0,
            'H2' => 0,
            'H3' => 0,
            'I5_OD' => 0,
            'I5_OS' => 0,
            'I6' => 0,
            'J1_OS' => 0,
            'J3_OD' => 0,
            'J3_OS' => 0,
            'O1.2.OD' => 0,
            'O1.3.OD' => 0,
            'O1.4.OD' => 0,
            'O1.5.OD' => 0,
            'O1.6.OD' => 0,
            'O1.7.OD' => 0,
            'O1.8.OD' => 0,
            'O1.9.OD' => 0,
            'O1.10.OD' => 0,
            'O1.11.OD' => 0,
            'O1.13.OD' => 0,
            'O1.1.OS' => 0,
            'O1.2.OS' => 0,
            'O1.3.OS' => 0,
            'O1.4.OS' => 0,
            'O1.5.OS' => 0,
            'O1.6.OS' => 0,
            'O1.7.OS' => 0,
            'O1.8.OS' => 0,
            'O1.9.OS' => 0,
            'O1.10.OS' => 0,
            'O1.11.OS' => 0,
            'O1.13.OS' => 0,
            'O2.OD' => 0,
            'O2.OS' => 0,
            'Iris.color.OD' => 0,
            'Iris.color.OS' => 0,
            'Q1.OD' => 0,
            'Q1.OS' => 0,
            'Q2.OD' => 0,
            'Q2.OS' => 0,
            'Q3.OD' => 0,
            'Q3.OS' => 0,
            'P1.OD' => 0,
            'P1.OS' => 0,
            'logMAR.L1_OD' => 0,
            'logMAR.L1_OS' => 0,
            'logMAR.L2_OD' => 0,
            'logMAR.L2_OS' => 0,
            'logMAR.L3_OD' => 0,
            'logMAR.L3_OS' => 0,
            'logMAR.L7_OD' => 0,
            'logMAR.L7_OS' => 0,
            'HTN.NCD' => 0,
            'Smoking.Status' => 0,
            'BMI' => 0,
            'Smoking' => 0,
            'DR.OS' => 0,
            'HTN.SBP' => 0,
            'HTN.DBP' => 0,
            'HTN.self.report' => 0,
            'Drusen.Subject' => 0,
            'Myopia_OD' => 0,
            'Myopia_OD1' => 0,
            'HighMyopia_OD' => 0,
            'Hyperopia_OD' => 0,
            'HighHyperopia_OD' => 0,
            'Catarct_OD' => 0,
            'SmokingC' => 0,
            'Iris.color.ODC' => 0,
            'Age' => 0,
            'Sex.A1' => 0
        ];

        // Map basic demographic data
        if (isset($formData['age'])) {
            $features['Age'] = (int) $formData['age'];
        }
        
        if (isset($formData['gender'])) {
            $features['Sex.A1'] = $formData['gender'] == 'male' ? 1 : 0;
        }
        
        // Map BMI
        if (isset($formData['bmi'])) {
            $features['BMI'] = (float) $formData['bmi'];
        } elseif (isset($formData['waist_circumference'])) {
            // Calculate approximate BMI if not provided but waist circumference is
            $bmiValue = $this->mapFrequencyToValue($formData['waist_circumference']);
            $features['BMI'] = $bmiValue * 5 + 20; // Approximate conversion
        }
        
        // Map diabetes
        if (isset($formData['diabetes'])) {
            $features['Diabetes'] = $this->mapFrequencyToBinary($formData['diabetes']);
        }
        
        // Map fasting blood sugar (FBS)
        if (isset($formData['fasting_blood_sugar'])) {
            $features['FBS'] = $this->mapFrequencyToGlucose($formData['fasting_blood_sugar']);
        }
        
        // Map blood pressure
        if (isset($formData['blood_pressure'])) {
            $bpValue = $this->mapFrequencyToValue($formData['blood_pressure']);
            $features['HTN.SBP'] = $bpValue * 20 + 100; // Approximate SBP
            $features['HTN.DBP'] = $bpValue * 10 + 70;  // Approximate DBP
        }
        
        // Map cholesterol
        if (isset($formData['high_cholesterol'])) {
            $features['CHOL'] = $this->mapFrequencyToCholesterol($formData['high_cholesterol']);
        }
        
        // Map smoking
        if (isset($formData['current_smoking'])) {
            $features['Smoking'] = $this->mapFrequencyToBinary($formData['current_smoking']);
            $features['SmokingC'] = $this->mapFrequencyToBinary($formData['current_smoking']);
        }
        
        // Map HDL
        if (isset($formData['high_lipids'])) {
            $features['HDL'] = $this->mapFrequencyToHDL($formData['high_lipids']);
        }
        
        // Map socioeconomic status to various features
        if (isset($formData['socioeconomic_status'])) {
            $sesValue = $this->mapFrequencyToValue($formData['socioeconomic_status']);
            // Map to multiple related features
            $features['E1'] = $sesValue;
            $features['E2'] = $sesValue;
        }
        
        // Map sunlight exposure
        if (isset($formData['sunlight_exposure'])) {
            $features['E4'] = $this->mapFrequencyToValue($formData['sunlight_exposure']);
        }
        
        // Map exercise
        if (isset($formData['current_regular_exercise'])) {
            $features['F1'] = $this->mapFrequencyToValue($formData['current_regular_exercise']);
        }
        
        if (isset($formData['past_regular_exercise'])) {
            $features['F2'] = $this->mapFrequencyToValue($formData['past_regular_exercise']);
        }
        
        // Map family history
        if (isset($formData['family_amd'])) {
            $features['H2'] = $this->mapFrequencyToBinary($formData['family_amd']);
        }
        
        if (isset($formData['family_eye_disease'])) {
            $features['H3'] = $this->mapFrequencyToBinary($formData['family_eye_disease']);
        }
        
        // Map eye conditions
        if (isset($formData['glaucoma'])) {
            $features['J3_OD'] = $this->mapFrequencyToBinary($formData['glaucoma']);
            $features['J3_OS'] = $this->mapFrequencyToBinary($formData['glaucoma']);
        }
        
        if (isset($formData['diabetic_retinopathy'])) {
            $features['DR.OS'] = $this->mapFrequencyToBinary($formData['diabetic_retinopathy']);
        }
        
        if (isset($formData['cataract_surgery'])) {
            $features['Catarct_OD'] = $this->mapFrequencyToBinary($formData['cataract_surgery']);
        }
        
        if (isset($formData['drusen'])) {
            $features['Drusen.Subject'] = $this->mapFrequencyToBinary($formData['drusen']);
        }
        
        // Map refractive errors
        if (isset($formData['refractive_errors'])) {
            if ($formData['refractive_errors'] == 'نزدیک بینی') {
                $features['Myopia_OD'] = 1;
                $features['Myopia_OD1'] = 1;
            } elseif ($formData['refractive_errors'] == 'دوربینی') {
                $features['Hyperopia_OD'] = 1;
                $features['HighHyperopia_OD'] = 1;
            }
        }
        
        if (isset($formData['refractive_error_severity'])) {
            $severity = $this->mapFrequencyToValue($formData['refractive_error_severity']);
            $features['Myopia_OD'] = $severity > 0.5 ? 1 : 0;
            $features['HighMyopia_OD'] = $severity > 0.8 ? 1 : 0;
        }
        
        // Map iris color
        if (isset($formData['iris_color'])) {
            $features['Iris.color.OD'] = $this->mapFrequencyToValue($formData['iris_color']);
            $features['Iris.color.OS'] = $this->mapFrequencyToValue($formData['iris_color']);
            $features['Iris.color.ODC'] = $this->mapFrequencyToValue($formData['iris_color']);
        }
        
        // Map lens opacity
        if (isset($formData['lens_opacity'])) {
            $features['O1.2.OD'] = $this->mapFrequencyToValue($formData['lens_opacity']);
            $features['O1.2.OS'] = $this->mapFrequencyToValue($formData['lens_opacity']);
        }
        
        // Map corrected vision
        if (isset($formData['best_corrected_vision'])) {
            $visionValue = $this->mapFrequencyToValue($formData['best_corrected_vision']);
            $logMAR = (1 - $visionValue) * 1.0; // Convert to logMAR scale
            $features['logMAR.L1_OD'] = $logMAR;
            $features['logMAR.L1_OS'] = $logMAR;
        }
        
        return $features;
    }
    
    /**
     * Helper method to map frequency values to numerical values
     */
    private function mapFrequencyToValue($frequency)
    {
        $mapping = [
            'very_high' => 1.0,
            'high' => 0.75,
            'moderate' => 0.5,
            'low' => 0.25,
            'very_low' => 0.0,
        ];
        
        return $mapping[$frequency] ?? 0.0;
    }
    
    /**
     * Helper method to map frequency values to binary (0 or 1)
     */
    private function mapFrequencyToBinary($frequency)
    {
        $mapping = [
            'very_high' => 1,
            'high' => 1,
            'moderate' => 1,
            'low' => 0,
            'very_low' => 0,
        ];
        
        return $mapping[$frequency] ?? 0;
    }
    
    /**
     * Helper method to map frequency to glucose value
     */
    private function mapFrequencyToGlucose($frequency)
    {
        $mapping = [
            'very_high' => 180,
            'high' => 140,
            'moderate' => 110,
            'low' => 90,
            'very_low' => 80,
        ];
        
        return $mapping[$frequency] ?? 90;
    }
    
    /**
     * Helper method to map frequency to cholesterol value
     */
    private function mapFrequencyToCholesterol($frequency)
    {
        $mapping = [
            'very_high' => 240,
            'high' => 200,
            'moderate' => 180,
            'low' => 160,
            'very_low' => 140,
        ];
        
        return $mapping[$frequency] ?? 180;
    }
    
    /**
     * Helper method to map frequency to HDL value
     */
    private function mapFrequencyToHDL($frequency)
    {
        $mapping = [
            'very_high' => 70,
            'high' => 60,
            'moderate' => 50,
            'low' => 40,
            'very_low' => 30,
        ];
        
        return $mapping[$frequency] ?? 50;
    }
}