import pandas as pd
import requests
import urllib.parse

# Путь к CSV файлу
csv_file_path = "autohofe.csv"

# Загрузка данных
df = pd.read_csv(csv_file_path, delimiter=',', encoding='utf-8')

# Очистка заголовков от пробелов и символов
df.columns = df.columns.str.strip()

# Проверка наличия столбца 'Bezeichnung'
if 'Bezeichnung' not in df.columns:
    raise KeyError("Column 'Bezeichnung' not found in the DataFrame.")

# Преобразование значений в строку и замена NaN на пустую строку
df['Bezeichnung'] = df['Bezeichnung'].fillna('').astype(str)

# Ваш API-ключ Google Places
API_KEY = 'AIzaSyDQg5ZYaDqEYptkd7Mf4XeXSeEEh0KsefA'

def search_place_info(place_name):
    if not place_name.strip():
        return {
            'latitude': '',
            'longitude': '',
            'reviews': 'No information available',
            'photos': 'No information available'
        }
    
    # Формирование URL для поиска в Google Places API
    search_url = f"https://maps.googleapis.com/maps/api/place/textsearch/json?query={urllib.parse.quote(place_name)}&key={API_KEY}"

    try:
        response = requests.get(search_url)
        response.raise_for_status()  # Проверка успешного запроса
        results = response.json()
        
        if results.get('status') == 'OK' and results.get('results'):
            place = results['results'][0]
            latitude = place.get('geometry', {}).get('location', {}).get('lat', '')
            longitude = place.get('geometry', {}).get('location', {}).get('lng', '')
            reviews = place.get('user_ratings_total', 'No reviews available')
            photos = place.get('photos', [{'photo_reference': 'No photos available'}])
            photos = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' + photos[0]['photo_reference'] + '&key=' + API_KEY if photos else 'No photos available'
        else:
            latitude = ''
            longitude = ''
            reviews = 'No information available'
            photos = 'No information available'
        
        return {
            'latitude': latitude,
            'longitude': longitude,
            'reviews': reviews,
            'photos': photos
        }
    
    except requests.RequestException as e:
        print(f"Request failed: {e}")
        return {
            'latitude': '',
            'longitude': '',
            'reviews': 'Error retrieving reviews',
            'photos': 'Error retrieving photos'
        }
    except Exception as e:
        print(f"An error occurred: {e}")
        return {
            'latitude': '',
            'longitude': '',
            'reviews': 'Error retrieving reviews',
            'photos': 'Error retrieving photos'
        }

# Создание новых столбцов для дополнительной информации
df['Latitude'] = ""
df['Longitude'] = ""
df['Reviews'] = ""
df['Photos'] = ""

# Обновление DataFrame с дополнительной информацией
for index, row in df.iterrows():
    place_name = row['Bezeichnung']
    
    # Получаем дополнительную информацию
    info = search_place_info(place_name)
    
    df.at[index, 'Latitude'] = info.get('latitude', '')
    df.at[index, 'Longitude'] = info.get('longitude', '')
    df.at[index, 'Reviews'] = info.get('reviews', '')
    df.at[index, 'Photos'] = info.get('photos', '')

# Сохранение обновленного DataFrame в новый CSV файл
updated_csv_file_path = "updated_autohofe.csv"
df.to_csv(updated_csv_file_path, index=False, encoding='utf-8')

print(f"Updated data has been saved to {updated_csv_file_path}")
