<?php

namespace App\Services\Streami;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;

class StreamiClient
{
    private $baseUrl = 'https://streamed.pk/api';

    public function getLiveMatches()
    {
        return Cache::remember('streami_live', 60, function () {
            return $this->fetchFromApi('/matches/live');
        });
    }

    public function getTodayMatches()
    {
        return Cache::remember('streami_today', 300, function () {
            return $this->fetchFromApi('/matches/all-today');
        });
    }

    public function getAllMatches()
    {
        return Cache::remember('streami_all', 300, function () {
            return $this->fetchFromApi('/matches/all');
        });
    }

    private function fetchFromApi($endpoint)
    {
        $response = Http::withOptions([
            'verify' => false, // Disable SSL verification if needed, similar to original script
        ])->get($this->baseUrl . $endpoint);

        if ($response->successful()) {
            return $response->json();
        }

        return [];
    }

    public function getMatchById($id)
    {
        // Check cached data first
        $caches = ['streami_live', 'streami_today', 'streami_all'];
        
        foreach ($caches as $key) {
            $matches = Cache::get($key, []);
            foreach ($matches as $match) {
                if (($match['id'] ?? '') === $id) {
                    return $match;
                }
            }
        }
        
        // If not found, fetch all (which updates cache) and check
        $matches = $this->getAllMatches();
        foreach ($matches as $match) {
            if (($match['id'] ?? '') === $id) {
                return $match;
            }
        }
        
        return null;
    }

    public function findMatch($homeTeam, $awayTeam)
    {
        $matches = $this->getAllMatches();
        if (empty($matches)) return null;

        $homeTeam = strtolower(trim($homeTeam));
        $awayTeam = strtolower(trim($awayTeam));

        // Helper to normalize names (remove FC, etc)
        $normalize = function($name) {
            $remove = ['fc', 'cf', 'fk', 'sc', 'united', 'city', 'real', 'atletico', 'inter', 'ac', 'as', 'sv', 'w'];
            $name = strtolower($name);
            foreach ($remove as $word) {
                $name = str_replace(' ' . $word . ' ', ' ', ' ' . $name . ' ');
            }
            return trim($name);
        };

        $normHome = $normalize($homeTeam);
        $normAway = $normalize($awayTeam);

        foreach ($matches as $match) {
            if (!isset($match['teams'])) continue;

            $apiHome = strtolower($match['teams']['home']['name'] ?? '');
            $apiAway = strtolower($match['teams']['away']['name'] ?? '');
            
            $normApiHome = $normalize($apiHome);
            $normApiAway = $normalize($apiAway);

            // Direct match
            if ($apiHome === $homeTeam && $apiAway === $awayTeam) return $match;

            // Normalized match
            if ($normApiHome === $normHome && $normApiAway === $normAway) return $match;

            // Fuzzy match (contains)
            if ((strpos($apiHome, $normHome) !== false || strpos($normHome, $apiHome) !== false) &&
                (strpos($apiAway, $normAway) !== false || strpos($normAway, $apiAway) !== false)) {
                return $match;
            }
            
            // Levenshtein check for close matches
            if ($this->isSimilar($normHome, $normApiHome) && $this->isSimilar($normAway, $normApiAway)) {
                return $match;
            }
        }

        return null;
    }

    private function isSimilar($str1, $str2)
    {
        if (empty($str1) || empty($str2)) return false;
        $lev = levenshtein($str1, $str2);
        $len = max(strlen($str1), strlen($str2));
        return ($lev / $len) < 0.3; // 30% difference tolerance
    }

    public function getStream($source, $id)
    {
        $url = $this->baseUrl . "/stream/$source/$id";
        
        $response = Http::withOptions([
            'verify' => false,
        ])->get($url);

        if ($response->successful()) {
            return $response->json();
        }
        
        return null;
    }
}
