#!/usr/bin/env python3
"""designer — 구(區) 빠짐 보충 자료 받기(카드 t_f4a6c3e5). 일회성.

왜: osm_admin_places.py 는 place=borough 점만 받는다. 부산 서구·동구, 대구 동구는 OSM 에 place=suburb 로 태그돼 있어
    입력 자료(kr_admin_places.json)에 아예 들어오지 않았다(DUP_KM 규칙 탓 아님 — 그 규칙은 같은 이름·같은 rank·15km 안만 합침).
무엇: 7대 특별·광역시 상자마다 OSM place=suburb|borough 점 중 이름이 '구'로 끝나는 것을 받아
      data/kr_gu_suburbs.json 에 쌓는다(이름·place·좌표·OSM node id). admin_labels.py 가 이 파일로 빠진 구만 보충한다.
      상자는 작게 — 남한 전체를 한 번에 물으면 공용 Overpass 가 504 로 끊는다(2026-10-14 확인).
사용: python3 osm_gu_check.py --out kr_gu_suburbs.json   (받은 상자는 건너뛰고 이어서 받음. 쓰는 파일은 --out 하나, 폴더 만들지 않음)
조회 시각: 2026-10-14 04:51 KST(결과 파일 'fetched'). 조회식 = 아래 Q, 상자 = 아래 BOXES.
OSM 데이터 © OpenStreetMap 기여자, ODbL 1.0 https://opendatacommons.org/licenses/odbl/1-0/
"""
import argparse
import json
import os
import subprocess
import time

EP = ['https://overpass.kumi.systems/api/interpreter', 'https://overpass-api.de/api/interpreter',
      'https://overpass.private.coffee/api/interpreter']
# 특별·광역시 상자(남, 서, 북, 동) — 시 경계를 넉넉히 덮음
BOXES = {
    '서울': (37.40, 126.75, 37.72, 127.20),
    '인천': (37.35, 126.35, 37.65, 126.80),
    '부산': (35.00, 128.85, 35.30, 129.25),
    '대구': (35.75, 128.45, 36.05, 128.80),
    '광주': (35.05, 126.70, 35.25, 127.00),
    '대전': (36.20, 127.25, 36.50, 127.55),
    '울산': (35.45, 129.20, 35.65, 129.50),
}
Q = '[out:json][timeout:60];node({},{},{},{})["place"~"^(suburb|borough)$"]["name"~"구$"];out;'


def ask(box):
    for attempt in range(4):
        r = subprocess.run(['curl', '-s', '-m', '70', '-A', 'rich-rider-designer/1.0 (one-off gu audit)',
                            '--data-urlencode', 'data=' + Q.format(*box), EP[attempt % len(EP)]], capture_output=True)
        try:
            return json.loads(r.stdout)['elements']
        except Exception:
            time.sleep(5)
    return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--out', required=True)
    OUT = ap.parse_args().out
    data = json.load(open(OUT)) if os.path.exists(OUT) else {'done': [], 'nodes': {}}
    for city, box in BOXES.items():
        if city in data['done']:
            continue
        els = ask(box)
        if els is None:
            print(f'{city}: 받기 실패 — 다시 돌리면 이어서', flush=True)
            continue
        for e in els:
            t = e['tags']
            data['nodes'][str(e['id'])] = {'name': t['name'], 'place': t['place'], 'city': city,
                                           'lon': e['lon'], 'lat': e['lat']}
        data['done'].append(city)
        data['note'] = 'OSM place=suburb|borough 점 중 이름이 구로 끝나는 것. © OpenStreetMap 기여자, ODbL 1.0.'
        data['fetched'] = time.strftime('%Y-%m-%d %H:%M')
        json.dump(data, open(OUT, 'w'), ensure_ascii=False, indent=0)
        print(f'{city}: {len(els)}점', flush=True)
        time.sleep(2)
    print(f'상자 {len(data["done"])}/{len(BOXES)} → {OUT}')


if __name__ == '__main__':
    main()
