deckhearth/scripts/import-lorcana.js

160 lines
4.9 KiB
JavaScript
Raw Normal View History

import fetch from 'node-fetch';
import fs from 'fs';
// Lorcana sets to import
const LORCANA_SETS = [
{ code: 'tfc', name: 'The First Chapter', lorcastCode: '1' },
{ code: 'rotf', name: 'Rise of the Floodborn', lorcastCode: '2' },
{ code: 'ink', name: 'Into the Inklands', lorcastCode: '3' }
];
// Helper function to delay execution
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Helper function to fetch with retry logic
async function fetchWithRetry(url, maxRetries = 3, delayMs = 2000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch(url, {
headers: {
'User-Agent': 'Deck-Hearth/1.0',
'Accept': 'application/json'
},
timeout: 30000 // 30 second timeout
});
if (response.ok) {
return response;
}
// If it's a 404, don't retry
if (response.status === 404) {
throw new Error(`Set not found: ${response.status}`);
}
// If it's a 504 or 503, wait longer before retry
if (response.status === 504 || response.status === 503) {
console.log(`Attempt ${attempt}: Got ${response.status}, waiting ${delayMs * attempt}ms before retry...`);
await delay(delayMs * attempt);
continue;
}
throw new Error(`Lorcana API error: ${response.status}`);
} catch (error) {
if (attempt === maxRetries) {
throw error;
}
console.log(`Attempt ${attempt} failed:`, error.message);
await delay(delayMs * attempt);
}
}
}
async function importLorcanaSet(setCode, setName, lorcastCode) {
try {
console.log(`\n🎨 Importing Lorcana set: ${setName} (${setCode})`);
// Fetch cards directly from Lorcast API
const response = await fetchWithRetry(`https://api.lorcast.com/v0/cards/search?q=set:${lorcastCode}&unique=prints`);
const data = await response.json();
const cards = data.results || [];
if (cards.length === 0) {
console.log(`❌ No cards found for set ${setName}`);
return { success: false, error: 'No cards found', importedCount: 0 };
}
console.log(`📊 Found ${cards.length} cards for set ${setName}`);
let importedCount = 0;
let skippedCount = 0;
// Import all cards via our API in a single batch
const importResponse = await fetch('http://localhost:3000/api/cards/import-lorcana', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
setCode: setCode,
setName: setName
})
});
const importResult = await importResponse.json();
if (importResult.success) {
importedCount = importResult.imported || 0;
skippedCount = importResult.skipped || 0;
console.log(`✅ Import completed for ${setName}: ${importedCount} imported, ${skippedCount} skipped`);
} else {
console.log(`❌ Failed to import ${setName}: ${importResult.error}`);
return { success: false, error: importResult.error };
}
return { success: true, importedCount, skippedCount, total: cards.length };
} catch (error) {
console.log(`❌ Error importing ${setName}: ${error.message}`);
return { success: false, error: error.message };
}
}
async function importAllLorcana() {
console.log('🎨 Starting Lorcana card import...\n');
const results = {
total: 0,
successful: 0,
failed: 0,
sets: []
};
for (const set of LORCANA_SETS) {
const result = await importLorcanaSet(set.code, set.name, set.lorcastCode);
results.sets.push({ ...set, ...result });
if (result.success) {
results.successful++;
results.total += result.importedCount || 0;
} else {
results.failed++;
}
// Add a delay between sets
await delay(2000);
}
// Print summary
console.log('\n📊 Lorcana Import Summary:');
console.log('========================');
console.log(`Total sets: ${LORCANA_SETS.length}`);
console.log(`Successful: ${results.successful}`);
console.log(`Failed: ${results.failed}`);
console.log(`Total cards imported: ${results.total}`);
console.log(`Success rate: ${((results.successful / LORCANA_SETS.length) * 100).toFixed(1)}%`);
// Save detailed results
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `lorcana-import-results-${timestamp}.json`;
fs.writeFileSync(filename, JSON.stringify(results, null, 2));
console.log(`\n📄 Detailed results saved to: ${filename}`);
return results;
}
// Run the import if this script is executed directly
if (import.meta.url === `file://${process.argv[1]}`) {
importAllLorcana()
.then(() => {
console.log('\n🎉 Lorcana import completed!');
process.exit(0);
})
.catch((error) => {
console.error('❌ Import failed:', error);
process.exit(1);
});
}
export { importAllLorcana, importLorcanaSet };