import googlemaps
import json
import time

# --- 配置 ---
API_KEY = 'AIzaSyBFXMXAMXplWh9zPXYnCcVtXhk3POkAEvY' # 请务必填入新生成的 Key
gmaps = googlemaps.Client(key=API_KEY)

# 限制设置
MAX_RESTAURANTS = 1000
processed_place_ids = set() 
all_sql_statements = []

TAG_MAPPING = {
    "halal": "tag_halal",
    "chinese_restaurant": "tag_chinese",
    "malay_restaurant": "tag_malay",
    "indian_restaurant": "tag_indian",
    "cafe": "tag_coffee",
    "bakery": "tag_dessert",
    "fast_food": "tag_fast_food",
    "vegetarian_restaurant": "tag_vegetarian",
    "bar": "tag_drinks",
}

def get_my_tags(google_types, name):
    found_tags = []
    if not google_types: google_types = []
    name_lower = name.lower()
    for g_type, my_tag in TAG_MAPPING.items():
        if g_type in google_types:
            found_tags.append(my_tag)
    if any(k in name_lower for k in ["spicy", "pedas", "mala"]): found_tags.append("tag_spicy")
    if "chicken" in name_lower: found_tags.append("tag_chicken")
    if "breakfast" in name_lower: found_tags.append("tag_breakfast")
    return list(set(found_tags))

def process_single_place(place_id):
    try:
        details = gmaps.place(place_id=place_id, fields=[
            'name', 'formatted_address', 'geometry', 'opening_hours', 
            'photo', 'type', 'rating', 'user_ratings_total'
        ]).get('result', {})

        name = details.get('name', '').replace("'", "''")
        address = details.get('formatted_address', '').replace("'", "''")
        loc = details.get('geometry', {}).get('location', {})
        lat, lng = loc.get('lat'), loc.get('lng')
        rating = details.get('rating', 0.0)
        visited = details.get('user_ratings_total', 0)

        images = []
        photo_data = details.get('photos') or details.get('photo')
        if photo_data:
            for p in photo_data[:3]:
                url = f"https://maps.googleapis.com/maps/api/place/photo?maxwidth=800&photoreference={p['photo_reference']}&key={API_KEY}"
                images.append({"url": url, "type": "image"})

        type_data = details.get('types') or details.get('type')
        tags = get_my_tags(type_data, name)

        sql = f"""
INSERT INTO `restaurants` (`created_by`, `name`, `latitude`, `longitude`, `address`, `logo_url`, `description`, `rating`, `visited_count`, `tags`, `images`) 
VALUES (1, '{name}', {lat}, {lng}, '{address}', '{images[0]['url'] if images else ''}', 'Auto-scraped 40km radius', {rating}, {visited}, '{json.dumps(tags)}', '{json.dumps(images)}');
SET @last_rest_id = LAST_INSERT_ID();"""
        
        if 'opening_hours' in details and 'periods' in details['opening_hours']:
            for p in details['opening_hours']['periods']:
                day = p['open']['day']
                db_day = 7 if day == 0 else day 
                open_t = f"{p['open']['time'][:2]}:{p['open']['time'][2:]}:00"
                close_t = f"{p['close']['time'][:2]}:{p['close']['time'][2:]}:00" if 'close' in p else "23:59:59"
                sql += f"\nINSERT INTO `opening_hours` (`restaurant_id`, `day_of_week`, `open_time`, `close_time`, `is_closed`) VALUES (@last_rest_id, {db_day}, '{open_t}', '{close_t}', 0);"
        
        return sql + "\n-- ----------------------------"
    except Exception as e:
        print(f"Error processing {place_id}: {e}")
        return None

def start_wide_scrape():
    # 中心点：1.875842, 102.944583
    # 设定 5 个主探测点（中心 + 四个方位稍微偏移），每个半径 40km，确保覆盖更多结果
    center_points = [
        (1.875842, 102.944583), # 中心
        (1.9758, 102.9445),    # 偏北
        (1.7758, 102.9445),    # 偏南
        (1.8758, 103.0445),    # 偏东
        (1.8758, 102.8445)     # 偏西
    ]

    for lat, lng in center_points:
        page_token = None
        while True:
            if len(processed_place_ids) >= MAX_RESTAURANTS:
                return

            print(f"Searching near {lat}, {lng}, radius 40km... (Current count: {len(processed_place_ids)})")
            
            # 使用 nearby_search
            res = gmaps.places_nearby(
                location=(lat, lng),
                radius=40000,
                type='restaurant',
                page_token=page_token
            )

            for p in res.get('results', []):
                pid = p['place_id']
                if pid not in processed_place_ids:
                    sql = process_single_place(pid)
                    if sql:
                        all_sql_statements.append(sql)
                        processed_place_ids.add(pid)
                    
                    if len(processed_place_ids) >= MAX_RESTAURANTS:
                        return

            # 处理翻页 (Google 允许最多 3 页，即 60 个结果)
            page_token = res.get('next_page_token')
            if not page_token:
                break
            
            # 翻页必须等待 2 秒，否则 Google 会返回 INVALID_REQUEST
            time.sleep(2)

# --- 执行 ---
start_wide_scrape()

filename = 'bp_40km_radius_1000.sql'
with open(filename, 'w', encoding='utf-8') as f:
    f.write("SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS = 0;\n")
    for s in all_sql_statements:
        f.write(s + "\n")

print(f"Done! Saved to {filename}")