import json


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

    for node in data["nodes"]:
        if "parameters" in node and "jsCode" in node["parameters"]:
            print(f"Updating jsCode in node: {node.get('name', 'unknown')}")
            node["parameters"]["jsCode"] = new_js_code
            break

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


# New jsCode for video search (already updated)
js_code_video_search = """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
  }
};"""

# New jsCode for simple workflow
js_code_simple = """// 處理 Momentry 搜尋結果
const data = $input.first().json;
const hits = data.hits;

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

// 格式化結果
const formattedResults = hits.map((hit, idx) => {
  return {
    index: idx + 1,
    id: hit.id,
    title: hit.title,
    text: hit.text,
    startTime: hit.start,
    endTime: hit.end,
    relevance: Math.round(hit.score * 100) + '%',
    file_path: hit.file_path
  };
});

return {
  json: {
    success: true,
    query: data.query,
    totalFound: data.count,
    results: formattedResults
  }
};"""

# New jsCode for RAG MCP workflow
js_code_rag = """// Process Momentry Core search results
const data = $input.first().json;
const hits = data.hits || [];

if (hits.length === 0) {
  return {
    json: {
      success: false,
      message: 'No relevant results found',
      query: data.query,
      results: []
    }
  };
}

// Format results for RAG
const formattedResults = hits.map((hit, idx) => {
  return {
    index: idx + 1,
    id: hit.id || hit.chunk_id,
    title: hit.title || 'Unknown Video',
    text: hit.text || hit.content || '',
    startTime: hit.start_time || hit.start || 0,
    endTime: hit.end_time || hit.end || 0,
    relevance: Math.round((hit.score || 0) * 100) + '%',
    videoUuid: hit.video_uuid || hit.uuid,
    file_path: hit.file_path || ''
  };
});

// Build context for RAG
const context = formattedResults
  .map(r => \`[\${r.index}] \${r.text} (Video: \${r.title}, Time: \${r.startTime}s-\${r.endTime}s)\`)
  .join('\\n\\n');

return {
  json: {
    success: true,
    query: data.query,
    totalFound: data.count || hits.length,
    context: context,
    results: formattedResults
  }
};"""

if __name__ == "__main__":
    # Update simple workflow
    update_file("docs/n8n_workflow_simple.json", js_code_simple)
    # Update RAG workflow
    update_file("docs/n8n_workflow_video_rag_mcp.json", js_code_rag)
    # Note: video search already updated, but we can re-update if needed
    # update_file('docs/n8n_workflow_video_search.json', js_code_video_search)
    print("All workflows updated.")
