import re

with open("app/modules/manual/backend/router.py", "r") as f:
    content = f.read()

if "from fastapi import" in content and "BackgroundTasks" not in content:
    content = content.replace("from fastapi import ", "from fastapi import BackgroundTasks, ")

if "def get_manual_article(slug: str):" in content:
    content = content.replace("def get_manual_article(slug: str):", "def get_manual_article(slug: str, background_tasks: BackgroundTasks):")

bg_def = """
def _increment_use_count(manual_id: str):
    try:
        execute_query(
            "UPDATE manual_articles SET use_count = COALESCE(use_count, 0) + 1 WHERE id = %s",
            (manual_id,)
        )
    except Exception as e:
        logger.error(f"Failed to increment use_count for manual {manual_id}: {e}")

@router.get("/{slug}")
"""
content = content.replace('@router.get("/{slug}")', bg_def)

target_inc = """    execute_query(
        "UPDATE manual_articles SET use_count = COALESCE(use_count, 0) + 1 WHERE id = %s",
        (article["id"],),
    )"""
new_inc = """    # Increment view async to save latency
    background_tasks.add_task(_increment_use_count, article["id"])"""
content = content.replace(target_inc, new_inc)

with open("app/modules/manual/backend/router.py", "w") as f:
    f.write(content)
