#!/usr/bin/env python3
"""Replace hardcoded db/*.db paths with db_path() for multi-instance support."""
from __future__ import annotations

import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent / "bot"
IMPORT_LINE = "from utils.db_paths import db_path\n"

# "db/file.db" or 'db/file.db' — not already wrapped in db_path(
PATTERN = re.compile(
    r"""(?<!db_path\()(?P<q>['"])db/(?P<name>[\w.-]+\.db)(?P=q)"""
)


def ensure_import(text: str) -> str:
    if "from utils.db_paths import db_path" in text:
        return text
    # Insert after module doc/header block or at top after shebang
    lines = text.splitlines(keepends=True)
    insert_at = 0
    for i, line in enumerate(lines):
        if line.startswith("# ╚") or line.startswith(" */"):
            insert_at = i + 1
            break
        if line.startswith("import ") or line.startswith("from "):
            insert_at = i
            break
    lines.insert(insert_at, IMPORT_LINE)
    if insert_at > 0 and not lines[insert_at - 1].endswith("\n\n"):
        # ensure blank line after header
        pass
    return "".join(lines)


def patch_file(path: Path) -> bool:
    text = path.read_text(encoding="utf-8", errors="replace")
    if path.name == "db_paths.py":
        return False

    def repl(match: re.Match) -> str:
        name = match.group("name")
        q = match.group("q")
        return f"db_path({q}{name}{q})"

    new_text, count = PATTERN.subn(repl, text)
    if count == 0:
        return False

    if "db_paths" not in path.parts:
        new_text = ensure_import(new_text)

    path.write_text(new_text, encoding="utf-8")
    print(f"  {path.relative_to(ROOT)}: {count} replacement(s)")
    return True


def main() -> None:
    updated = 0
    for path in sorted(ROOT.rglob("*.py")):
        if "__pycache__" in path.parts:
            continue
        if patch_file(path):
            updated += 1
    print(f"Updated {updated} files")


if __name__ == "__main__":
    main()
