import { CompanyDatabase } from './build/database/db.js';
import { readFileSync } from 'fs';
import { resolve } from 'path';
console.log('📊 Importing extracted financial data into database...\n');
const db = new CompanyDatabase();
const summaryPath = resolve('./data/extracted/all_financial_data.json');
try {
const data = JSON.parse(readFileSync(summaryPath, 'utf-8'));
console.log(`Found ${data.length} financial records to import\n`);
let imported = 0;
let skipped = 0;
let errors = 0;
for (const record of data) {
try {
// Extract org_nr from filename (format: aarsregnskap_999059198-2023.pdf)
const orgNrMatch = record.file?.match(/(\d{9})/);
const orgNr = orgNrMatch ? orgNrMatch[1] : '999059198'; // Default to test company
console.log(`Importing ${record.year} for org ${orgNr}...`);
// Check if this data already exists
const existing = db.getFinancialHistory(orgNr, 1).find((r) => r.year === record.year);
if (existing && existing.source !== 'estimated') {
console.log(` ⏭️ Skipped ${record.year} - already exists with source: ${existing.source}`);
skipped++;
continue;
}
// Insert into database
db.insertFinancialSnapshot({
org_nr: orgNr,
year: record.year,
revenue: record.revenue,
profit: record.profit,
assets: record.assets,
equity: record.equity,
employees: null,
source: 'openai_vision_extraction'
});
console.log(` ✅ Imported ${record.year}: Revenue=${record.revenue ? (record.revenue/1000000).toFixed(1) + 'M' : 'N/A'}, Profit=${record.profit ? (record.profit/1000000).toFixed(1) + 'M' : 'N/A'}`);
imported++;
} catch (error) {
console.error(` ❌ Error importing ${record.year}: ${error.message}`);
errors++;
}
}
console.log('\n' + '='.repeat(60));
console.log('📊 IMPORT SUMMARY');
console.log('='.repeat(60));
console.log(`✅ Successfully imported: ${imported} records`);
console.log(`⏭️ Skipped (already exists): ${skipped} records`);
console.log(`❌ Errors: ${errors} records`);
console.log('='.repeat(60));
// Verify the data
console.log('\n🔍 Verifying imported data...');
const allData = db.getFinancialHistory('999059198', 20);
console.log(`\n📅 Found ${allData.length} years in database:`);
allData.forEach(d => {
console.log(` ${d.year}: Revenue=${d.revenue ? (d.revenue/1000000).toFixed(1) + 'M NOK' : 'N/A'}, Source=${d.source}`);
});
console.log('\n✅ Import complete!\n');
} catch (error) {
console.error('❌ Import failed:', error.message);
console.error(error.stack);
process.exit(1);
}