from fliiq.runtime.security import check_path_allowed


async def handler(params: dict) -> dict:
    """Replace a unique occurrence of old_text with new_text in a file."""
    path = params["path"]
    check_path_allowed(path)
    old_text = params["old_text"]
    new_text = params["new_text"]

    with open(path, "r") as f:
        content = f.read()

    count = content.count(old_text)
    if count == 0:
        raise ValueError(f"old_text not found in {path}")
    if count > 1:
        raise ValueError(f"old_text found {count} times in {path} — must be unique")

    updated = content.replace(old_text, new_text, 1)

    with open(path, "w") as f:
        f.write(updated)

    # Show a short snippet around the change
    idx = updated.find(new_text)
    start = max(0, idx - 40)
    end = min(len(updated), idx + len(new_text) + 40)
    snippet = updated[start:end]

    return {"result": f"Edited {path}:\n...{snippet}..."}
