import os
import re

file_path = r'D:\cnf\chatbot-canifa-feedback\backend\api\bulk_ops_route.py'
with open(file_path, 'r', encoding='utf-8') as f:
    content = f.read()

# Replace bulk_ai_edit and bulk_ai_edit_preview
# We'll just replace the entire bulk_ai_edit function safely using a regex up to bulk_ai_edit_preview definition
new_bulk_ai_edit = '''@router.post("/ai-edit", summary="Bulk AI-powered field editing with Codex")
async def bulk_ai_edit(req: BulkAiEditRequest):
    """
    Push Codex-powered mass edit jobs to Redis Queue for the worker.
    """
    if not req.codes:
        return JSONResponse(status_code=400, content={"status": "error", "message": "Trống codes"})
    if req.target_field not in FIELD_OPTIONS and req.target_field not in _FIELD_LABELS:
        return JSONResponse(status_code=400, content={
            "status": "error",
            "message": f"Trường '{req.target_field}' không hợp lệ. Chọn: {', '.join(FIELD_OPTIONS.keys())}"
        })
    if not req.instruction.strip():
        return JSONResponse(status_code=400, content={"status": "error", "message": "Thiếu instruction"})

    redis = redis_cache.get_client()
    if not redis:
        return JSONResponse(status_code=500, content={"status": "error", "message": "Redis is not available"})
        
    latest_job = await redis.get("ai_edit:progress:latest_job")
    if latest_job:
        status_data = await redis.hgetall(f"ai_edit:progress:{latest_job.decode('utf-8') if isinstance(latest_job, bytes) else latest_job}")
        if status_data and status_data.get(b"is_running", status_data.get("is_running")) in (b"true", "true"):
            return JSONResponse(status_code=409, content={
                "status": "error", "message": "Đang có task AI chạy. Vui lòng đợi hoàn tất."
            })

    import uuid
    job_id = f"ai_edit_{uuid.uuid4().hex[:8]}"
    job_data = {
        "job_id": job_id,
        "codes": req.codes,
        "target_field": req.target_field,
        "instruction": req.instruction,
        "mode": req.mode
    }

    await redis.lpush("ai_edit:queue", import_json.dumps(job_data))
    await redis.set("ai_edit:progress:latest_job", job_id)
    
    # Initialize progress state
    await redis.hset(f"ai_edit:progress:{job_id}", mapping={
        "is_running": "true",
        "total": len(req.codes),
        "done": 0,
        "errors": 0,
        "current_code": req.codes[0] if req.codes else "",
        "current_name": "",
        "results": "[]"
    })

    return {
        "status": "success",
        "message": f"Đã đẩy {len(req.codes)} SP vào worker để sinh tự động nội dung AI...",
        "total": len(req.codes),
    }

'''

content = re.sub(
    r'@router\.post\("/ai-edit", summary="Bulk AI-powered field editing with Codex"\)\s*async def bulk_ai_edit.*?return \{\s*"status": "success",\s*"message": .*?\s*"total": len\(req\.codes\),\s*\}\s*',
    new_bulk_ai_edit.replace('import_json', 'json'),
    content,
    flags=re.DOTALL
)

new_ai_edit_status = '''@router.get("/ai-edit-status", summary="Get progress of bulk AI edit")
async def ai_edit_status():
    redis = redis_cache.get_client()
    default_state = {
        "is_running": False,
        "total": 0,
        "done": 0,
        "errors": 0,
        "current_code": None,
        "current_name": None,
        "results": []
    }

    if not redis:
        return default_state
        
    latest_job_id = await redis.get("ai_edit:progress:latest_job")
    if not latest_job_id:
        return default_state
        
    latest_job_id = latest_job_id.decode("utf-8") if isinstance(latest_job_id, bytes) else latest_job_id
    status_data = await redis.hgetall(f"ai_edit:progress:{latest_job_id}")
    if not status_data:
        return default_state
        
    # parse bytes if needed
    status_parsed = {k.decode('utf-8') if isinstance(k, bytes) else k: v.decode('utf-8') if isinstance(v, bytes) else v for k,v in status_data.items()}
    
    import json
    results_str = status_parsed.get("results", "[]")
    try:
        results = json.loads(results_str)
    except:
        results = []
        
    return {
        "is_running": status_parsed.get("is_running") == "true",
        "total": int(status_parsed.get("total", 0)),
        "done": int(status_parsed.get("done", 0)),
        "errors": int(status_parsed.get("errors", 0)),
        "current_code": status_parsed.get("current_code", None),
        "current_name": status_parsed.get("current_name", None),
        "results": results
    }'''

content = re.sub(
    r'async def _run_bulk_ai_edit.*?logger\.info\(f"🏁 Bulk AI edit completed: \{BULK_AI_STATE\[\'done\'\]\}/\{BULK_AI_STATE\[\'total\'\]\} \(errors: \{BULK_AI_STATE\[\'errors\'\]\}\)"\)',
    '',
    content,
    flags=re.DOTALL
)

content = re.sub(
    r'@router\.get\("/ai-edit-status", summary="Get progress of bulk AI edit"\)\s*async def ai_edit_status\(\):\s*return BULK_AI_STATE',
    new_ai_edit_status,
    content,
    flags=re.DOTALL
)

with open(file_path, 'w', encoding='utf-8') as f:
    f.write(content)

print("done")
