import re

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

# 1. Ensure BackgroundTasks is imported
if "from fastapi import" in content and "BackgroundTasks" not in content:
    content = content.replace("from fastapi import ", "from fastapi import BackgroundTasks, ")

# 2. Add BackgroundTasks to the manual_detail function signature
target_def = "async def manual_detail(request: Request, slug: str):"
new_def = "async def manual_detail(request: Request, slug: str, background_tasks: BackgroundTasks):"
content = content.replace(target_def, new_def)

# 3. Define the background method if not existing
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("/manual/{slug}", response_class=HTMLResponse)
"""
content = content.replace('@router.get("/manual/{slug}", response_class=HTMLResponse)', bg_def)

# 4. Replace the execute_query in the endpoint
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/frontend/views.py", "w") as f:
    f.write(content)
