import json
import sys


def update_workflow(filename):
    with open(filename, "r", encoding="utf-8") as f:
        data = json.load(f)

    # Find the code node (index 2)
    for node in data["nodes"]:
        if (
            node.get("name") == "處理結果"
            or "parameters" in node
            and "jsCode" in node["parameters"]
        ):
            old_code = node["parameters"]["jsCode"]
            print("Old code length:", len(old_code))
            # New code without URL generation
            new_code = """const hits = $input.first().json.hits;

if (!hits || hits.length === 0) {
  return {
    json: {
      message: '找不到相關結果',
      query: $input.first().json.query
    }
  };
}

const results = hits.map((hit, index) => {
  return {
    number: index + 1,
    text: hit.text,
    start: hit.start,
    end: hit.end,
    score: Math.round(hit.score * 100) + '%',
    video_title: hit.title,
    file_path: hit.file_path
  };
});

return {
  json: {
    query: $input.first().json.query,
    count: $input.first().json.count,
    results: results
  }
};"""
            node["parameters"]["jsCode"] = new_code
            print("Updated jsCode")
            break

    with open(filename, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    print("File updated:", filename)


if __name__ == "__main__":
    update_workflow(sys.argv[1])
