#!/usr/bin/env bash
# 取込エラー（race_results 同着など）対策。git pull 不要。
#   cd /var/www/html/tools.kachiumaai.com
#   bash scripts/hotfix_import_jrvltsql_db.sh
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TARGET="$ROOT/collectors/import_jrvltsql_db.py"
if [[ ! -f "$TARGET" ]]; then
  echo "not found: $TARGET" >&2
  exit 1
fi
if grep -q 'from pymysql.err import IntegrityError' "$TARGET"; then
  echo "already patched: $TARGET"
  exit 0
fi
cp -a "$TARGET" "${TARGET}.bak.$(date +%Y%m%d%H%M%S)"
python3 - "$TARGET" <<'PY'
import sys
from pathlib import Path

path = Path(sys.argv[1])
text = path.read_text(encoding="utf-8")
text = text.replace(
    "from collectors.db_util import connect  # noqa: E402",
    "from pymysql.err import IntegrityError\n\nfrom collectors.db_util import connect  # noqa: E402\n\nCOMMIT_EVERY_RACES = 500",
)
text = text.replace(
    '    stats = {"ra_rows": 0, "races_upsert": 0, "se_rows": 0, "entries_upsert": 0, "results_upsert": 0, "skip": 0}',
    '    stats = {\n        "ra_rows": 0,\n        "races_upsert": 0,\n        "se_rows": 0,\n        "entries_upsert": 0,\n        "results_upsert": 0,\n        "results_skip": 0,\n        "entries_skip": 0,\n        "skip": 0,\n    }',
)
old = '''                else:
                    cur.execute(
                        """INSERT INTO race_entries (race_id, horse_id, bracket_number, horse_number, popularity)
                           VALUES (%s,%s,%s,%s,%s)""",
                        (race_id, horse_id, bracket, umaban, pop),
                    )
            stats["entries_upsert"] += 1

            if finish and finish > 0:
                cur.execute(
                    """SELECT id FROM race_results WHERE race_id=%s AND horse_id=%s LIMIT 1""",
                    (race_id, horse_id),
                )
                rr = cur.fetchone()
                if rr:
                    cur.execute(
                        "UPDATE race_results SET finish_position=%s WHERE id=%s",
                        (finish, rr["id"]),
                    )
                else:
                    cur.execute(
                        """INSERT INTO race_results (race_id, horse_id, finish_position)
                           VALUES (%s,%s,%s)""",
                        (race_id, horse_id, finish),
                    )
                stats["results_upsert"] += 1

    if not args.dry_run:
        conn.commit()'''
new = '''                else:
                    try:
                        cur.execute(
                            """INSERT INTO race_entries (race_id, horse_id, bracket_number, horse_number, popularity)
                               VALUES (%s,%s,%s,%s,%s)""",
                            (race_id, horse_id, bracket, umaban, pop),
                        )
                    except IntegrityError:
                        stats["entries_skip"] += 1
                        continue
            stats["entries_upsert"] += 1

            if finish and finish > 0:
                try:
                    cur.execute(
                        """INSERT INTO race_results (race_id, horse_id, finish_position)
                           VALUES (%s,%s,%s)
                           ON DUPLICATE KEY UPDATE finish_position=VALUES(finish_position)""",
                        (race_id, horse_id, finish),
                    )
                    stats["results_upsert"] += 1
                except IntegrityError:
                    stats["results_skip"] += 1

        if not args.dry_run and stats["races_upsert"] % COMMIT_EVERY_RACES == 0:
            conn.commit()

    if not args.dry_run:
        conn.commit()'''
if old not in text:
    print("patch target not found", file=sys.stderr)
    raise SystemExit(1)
path.write_text(text.replace(old, new), encoding="utf-8")
print("patched:", path)
PY
echo "[OK] hotfix applied"
