namespace :nico do
  desc 'ニコニコ DB 逆連携'
  task export: :environment do
    require 'open3'

    mysql_user = ENV.fetch('MYSQL_USER')
    mysql_pass = ENV.fetch('MYSQL_PASS')
    nizika_nico_path = ENV.fetch('NIZIKA_NICO_PATH')

    videos = Post.where('url LIKE ?', '%nicovideo.jp/watch/%').pluck(:url).filter_map {
      _1[%r{nicovideo\.jp/watch/([^/?#]+)}, 1]
    }.uniq

    next if videos.empty?

    _, stderr, status = Open3.capture3(
        { 'MYSQL_USER' => mysql_user, 'MYSQL_PASS' => mysql_pass },
        'python3', '-m', 'tracked_videos.put_bulk_upsert', *videos,
        chdir: nizika_nico_path)

    raise stderr unless status.success?
  end
end
