# 执行示例 bundle exec rake init_project_topic:project
# RAILS_ENV=production bundle exec rake init_project_topic:project

namespace :init_project_topic do
  desc "Init Project Topic for Project"
  task project: :environment do
    Project.where(platform: 'forge').order(created_at: :desc).find_each do |p|
      next unless p.owner.present? 
      next if p.project_topics.size >= 3
      begin 
        languages = $gitea_client.get_repos_languages_by_owner_repo(p.owner.login, p.identifier)
        topic_count = p.project_topics.size 
        languages.each do |k, _|
          next if topic_count >= 3
          project_topic = ProjectTopic.find_or_create_by!(name: k.downcase)
          project_topic_ralate = project_topic.project_topic_ralates.find_or_create_by!(project_id: p.id)
          if project_topic.present? && project_topic_ralate.present? 
            topic_count +=1
          end
        end
      rescue 
        next 
      end
    end
  end
end