#!/bin/bash
# 조석 API 백엔드 반영 폴링 — 살아나면 실데이터 저장
KEY="4947cc287648a8af2c65a30e68252d0a4c20b62c9229700c4d44e5b50f4c89f4"
HGL="https://apis.data.go.kr/1192136/tideFcstHghLw"
TIME="https://apis.data.go.kr/1192136/tideFcstTime"
OUT=/tmp/sea_tide_result
DATE=$(date +%Y%m%d)
for i in $(seq 1 12); do
  R=$(curl -s "${HGL}?serviceKey=${KEY}&pageNo=1&numOfRows=10&type=json&obsCode=DT_0018&reqDate=${DATE}")
  if [[ "$R" == *"{"* || "$R" == *"<"* ]] && [[ "$R" != "Unexpected errors" ]]; then
    echo "$R" > ${OUT}_hghlw.json
    curl -s "${TIME}?serviceKey=${KEY}&pageNo=1&numOfRows=30&type=json&obsCode=DT_0018&reqDate=${DATE}&min=60" > ${OUT}_time.json
    echo "SUCCESS attempt=$i date=${DATE} $(date '+%H:%M')" > ${OUT}_status.txt
    exit 0
  fi
  echo "attempt=$i still 500 ($(date '+%H:%M'))" >> ${OUT}_log.txt
  [ $i -lt 12 ] && sleep 1800
done
echo "EXHAUSTED after 12 attempts (6h)" > ${OUT}_status.txt
exit 1
