import { createClient } from '@libsql/client';
import { drizzle } from 'drizzle-orm/libsql';
import { eq, inArray } from 'drizzle-orm';
import fs from 'fs';
import { character, characterHistory } from '../src/lib/server/db/schema';

const DATABASE_URL = process.env.DATABASE_URL || 'file:local.db';

const client = createClient({ url: DATABASE_URL });
const db = drizzle(client);

function readJsonFile(path: string): string[] | null {
	if (!fs.existsSync(path)) {
		return null;
	}

	const content = fs.readFileSync(path, 'utf-8');
	return JSON.parse(content) as string[];
}

function getErrorMessage(error: unknown): string {
	return error instanceof Error ? error.message : String(error);
}

async function setDailyCharacters(): Promise<void> {
	try {
		const dailyCharacterIdsRaw = readJsonFile('./scripts/daily-characters.json');

		if (!dailyCharacterIdsRaw || dailyCharacterIdsRaw.length === 0) {
			throw new Error('No daily characters found in daily-characters.json');
		}

		const dailyCharacterIds = dailyCharacterIdsRaw;

		console.log(`\n=== Setting Daily Mode Characters ===\n`);
		console.log(`Found ${dailyCharacterIds.length} characters to set as daily\n`);

		// Step 1: Disable isInDailyMode for all characters
		console.log('Step 1: Disabling isInDailyMode for all characters...');
		await db.update(character).set({ isInDailyMode: false });
		console.log('✓ All characters disabled from daily mode\n');

		// Step 2: Enable isInDailyMode for characters in the list
		console.log('Step 2: Enabling isInDailyMode for daily characters...\n');

		let successCount = 0;
		let errorCount = 0;

		const existingCharacters = await db
			.select({ id: character.id })
			.from(character)
			.where(inArray(character.id, dailyCharacterIds));

		const existingIdSet = new Set(existingCharacters.map((c) => c.id));
		const missingIds = dailyCharacterIds.filter((id) => !existingIdSet.has(id));

		if (missingIds.length > 0) {
			errorCount += missingIds.length;
			console.error(`✗ ${missingIds.length} character ID(s) were not found in database:`);
			for (const missingId of missingIds) {
				console.error(`  - ${missingId}`);
			}
			console.error('');
		}

		for (let i = 0; i < dailyCharacterIds.length; i++) {
			const charId = dailyCharacterIds[i];
			if (!existingIdSet.has(charId)) {
				continue;
			}

			try {
				await db
					.update(character)
					.set({ isInDailyMode: true })
					.where(eq(character.id, charId));

				successCount++;
			} catch (error) {
				errorCount++;
				console.error(`\n✗ Error updating character ${i + 1}:`);
				console.error(`  ID: ${charId}`);
				console.error(`  Message: ${getErrorMessage(error)}`);
			}
		}

		console.log(`\n\n✓ Daily characters updated!`);
		console.log(`  Success: ${successCount}`);
		console.log(`  Errors: ${errorCount}`);

		if (errorCount === 0) {
			console.log(`\n✅ Successfully set ${successCount} characters as daily mode characters\n`);
		}

		// Step 3: Delete only today's character from characterHistory
        console.log('Step 3: Cleaning up today\'s characterHistory...');
		try {
			const todayDate = new Date(new Date().setHours(1, 0, 0, 0)).toISOString().split('T')[0];
			await db.delete(characterHistory).where(eq(characterHistory.date, todayDate));
            console.log(`✓ Character history cleared for ${todayDate}\n`);
        } catch (error) {
            console.error('✗ Error clearing character history:', getErrorMessage(error));
        }
	} catch (error) {
		console.error('✗ Operation failed:', getErrorMessage(error));
		process.exit(1);
	} finally {
		client.close();
	}
}

setDailyCharacters().catch((error) => {
	console.error(getErrorMessage(error));
	process.exit(1);
});
