<?php

namespace App\Command;

use App\Entity\Stats;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'app:update-city-coordinates',
    description: 'Met à jour les coordonnées de toutes les villes via l\'API Nominatim',
)]
class UpdateCityCoordinatesCommand extends Command
{
    public function __construct(
        private EntityManagerInterface $entityManager
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $stats = $this->entityManager->getRepository(Stats::class)->findAll();
        $total = count($stats);
        $updated = 0;
        $errors = 0;

        $io->progressStart($total);

        foreach ($stats as $stat) {
            if ($stat->getZone() && $stat->getZone() !== 'undefined' && preg_match('/^\d+$/', $stat->getZone())) {
                $cityName = $stat->getName() ?: $stat->getZone();
                
                // Vérifier si les coordonnées sont déjà présentes
                if (!$stat->getLat() || !$stat->getLon()) {
                    $coordinates = $this->getCityCoordinates($cityName, $stat->getZone());
                    
                    if ($coordinates) {
                        $stat->setLat((string) $coordinates['lat']);
                        $stat->setLon((string) $coordinates['lon']);
                        $this->entityManager->persist($stat);
                        $updated++;
                        $io->text("✓ $cityName ({$stat->getZone()}): " . $coordinates['lat'] . ", " . $coordinates['lon']);
                    } else {
                        $errors++;
                        $io->warning("✗ Impossible de récupérer les coordonnées pour $cityName ({$stat->getZone()})");
                    }
                }
            }
            
            $io->progressAdvance();
        }

        $this->entityManager->flush();
        $io->progressFinish();

        $io->success("Mise à jour terminée : $updated villes mises à jour, $errors erreurs");

        return Command::SUCCESS;
    }

    private function getCityCoordinates(string $cityName, string $inseeCode): ?array
    {
        // Stratégie 1: Nominatim
        $coordinates = $this->getCoordinatesFromNominatim($cityName);
        if ($coordinates) {
            return $coordinates;
        }

        // Stratégie 2: Premier objet Place townhall
        $coordinates = $this->getCoordinatesFromPlaceTownhall($inseeCode);
        if ($coordinates) {
            return $coordinates;
        }

        // Stratégie 3: N'importe quel objet Place
        $coordinates = $this->getCoordinatesFromAnyPlace($inseeCode);
        if ($coordinates) {
            return $coordinates;
        }

        // Stratégie 4: Addok
        return $this->getCoordinatesFromAddok($cityName, $inseeCode);
    }

    private function getCoordinatesFromNominatim(string $cityName): ?array
    {
        $query = urlencode($cityName . ', France');
        $url = "https://nominatim.openstreetmap.org/search?q={$query}&format=json&limit=1&countrycodes=fr";
        
        try {
            usleep(100000); // 0.1 seconde entre les appels
            
            $context = stream_context_create([
                'http' => [
                    'timeout' => 5,
                    'user_agent' => 'OSM-Commerces/1.0'
                ]
            ]);
            
            $response = file_get_contents($url, false, $context);
            
            if ($response === false) {
                return null;
            }
            
            $data = json_decode($response, true);
            
            if (!empty($data) && isset($data[0]['lat']) && isset($data[0]['lon'])) {
                return [
                    'lat' => (float) $data[0]['lat'],
                    'lon' => (float) $data[0]['lon']
                ];
            }
        } catch (\Exception $e) {
            // En cas d'erreur, on retourne null
        }
        
        return null;
    }

    private function getCoordinatesFromPlaceTownhall(string $inseeCode): ?array
    {
        $places = $this->entityManager->getRepository(\App\Entity\Place::class)
            ->createQueryBuilder('p')
            ->where('p.zip_code = :inseeCode')
            ->andWhere('p.lat IS NOT NULL')
            ->andWhere('p.lon IS NOT NULL')
            ->andWhere('p.main_tag = :mainTag')
            ->setParameter('inseeCode', $inseeCode)
            ->setParameter('mainTag', 'townhall')
            ->setMaxResults(1)
            ->getQuery()
            ->getResult();

        if (!empty($places)) {
            $place = $places[0];
            return [
                'lat' => (float) $place->getLat(),
                'lon' => (float) $place->getLon()
            ];
        }

        return null;
    }

    private function getCoordinatesFromAnyPlace(string $inseeCode): ?array
    {
        $places = $this->entityManager->getRepository(\App\Entity\Place::class)
            ->createQueryBuilder('p')
            ->where('p.zip_code = :inseeCode')
            ->andWhere('p.lat IS NOT NULL')
            ->andWhere('p.lon IS NOT NULL')
            ->setParameter('inseeCode', $inseeCode)
            ->setMaxResults(1)
            ->getQuery()
            ->getResult();

        if (!empty($places)) {
            $place = $places[0];
            return [
                'lat' => (float) $place->getLat(),
                'lon' => (float) $place->getLon()
            ];
        }

        return null;
    }

    private function getCoordinatesFromAddok(string $cityName, string $inseeCode): ?array
    {
        $query = urlencode($cityName . ', France');
        $url = "https://demo.addok.xyz/search?q={$query}&limit=1";
        
        try {
            $context = stream_context_create([
                'http' => [
                    'timeout' => 5,
                    'user_agent' => 'OSM-Commerces/1.0'
                ]
            ]);
            
            $response = file_get_contents($url, false, $context);
            
            if ($response === false) {
                return null;
            }
            
            $data = json_decode($response, true);
            
            if (!empty($data['features']) && isset($data['features'][0]['geometry']['coordinates'])) {
                $coordinates = $data['features'][0]['geometry']['coordinates'];
                return [
                    'lat' => (float) $coordinates[1], // Addok retourne [lon, lat]
                    'lon' => (float) $coordinates[0]
                ];
            }
        } catch (\Exception $e) {
            // En cas d'erreur, on retourne null
        }
        
        return null;
    }
} 