#!/usr/bin/env node
import { execSync } from 'child_process';

const EMBY_HOST = '145.239.143.92:8096';
const EMBY_API_KEY = 'e3e52b1dcb8b47c39d46b5256bf87081';

function curl(url, opts = '') {
  return execSync(`curl -s ${opts} "${url}"`, { encoding: 'utf8' });
}

async function loginJellyseerr() {
  const res = curl('http://145.239.143.92:5055/api/v1/auth/local', 
    `-X POST -H "Content-Type: application/json" -d '{"email":"admin","password":"admin"}' -i`);
  const match = res.match(/connect\.sid=([^;]+)/);
  if (!match) throw new Error('Login failed');
  return `connect.sid=${match[1]}`;
}

function getRecentRequests(cookie) {
  const data = curl('http://145.239.143.92:5055/api/v1/request?take=20&skip=0&sort=added&filter=all', 
    `-H "Cookie: ${cookie}"`);
  return JSON.parse(data);
}

function checkEmbyItem(tmdbId) {
  const data = curl(`http://${EMBY_HOST}/emby/Items?Recursive=true&AnyProviderIdEquals=Tmdb.${tmdbId}&api_key=${EMBY_API_KEY}`);
  return JSON.parse(data);
}

function refreshMetadata(itemId) {
  curl(`http://${EMBY_HOST}/emby/Items/${itemId}/Refresh?MetadataRefreshMode=FullRefresh&ImageRefreshMode=FullRefresh&ReplaceAllMetadata=true&ReplaceAllImages=true&api_key=${EMBY_API_KEY}`, '-X POST');
}

async function main() {
  const cookie = await loginJellyseerr();
  const requests = getRecentRequests(cookie);
  
  const now = Date.now();
  const oneDayAgo = now - 24 * 60 * 60 * 1000;
  const recent = requests.results.filter(r => new Date(r.createdAt).getTime() > oneDayAgo);
  
  if (recent.length === 0) {
    console.log('✅ 最近24小时无新求片');
    return;
  }
  
  const issues = [];
  const fixed = [];
  
  for (const req of recent) {
    const result = checkEmbyItem(req.media.tmdbId);
    
    if (result.Items.length === 0) continue;
    
    const item = result.Items[0];
    if (!item.ImageTags || Object.keys(item.ImageTags).length === 0) {
      issues.push(`${item.Name} (${item.Id})`);
      refreshMetadata(item.Id);
      fixed.push(item.Name);
    }
  }
  
  if (issues.length > 0) {
    console.log(`⚠️ 发现 ${issues.length} 个刮削问题，已触发修复：\n${fixed.join('\n')}`);
  } else {
    console.log(`✅ 检查完成，${recent.length} 个求片项刮削正常`);
  }
}

main().catch(console.error);
