import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
import { dirname, resolve } from 'path';

const CACHE_PATH = resolve('.cache', 'emby-user-context.json');

function ensureCacheDir() {
	const dir = dirname(CACHE_PATH);
	if (!existsSync(dir)) {
		mkdirSync(dir, { recursive: true });
	}
}

function normalizeGuid(value) {
	return typeof value === 'string' ? value.replace(/-/g, '').trim().toLowerCase() : '';
}

function loadCacheFile() {
	if (!existsSync(CACHE_PATH)) {
		return { users: {} };
	}

	try {
		const parsed = JSON.parse(readFileSync(CACHE_PATH, 'utf8'));
		return parsed && typeof parsed === 'object' ? parsed : { users: {} };
	} catch {
		return { users: {} };
	}
}

function saveCacheFile(cache) {
	ensureCacheDir();
	writeFileSync(CACHE_PATH, JSON.stringify(cache, null, 2));
}

export function readCachedEmbyUserContext(embyGuid) {
	const normalizedGuid = normalizeGuid(embyGuid);
	if (!normalizedGuid) return null;

	const cache = loadCacheFile();
	return cache.users?.[normalizedGuid] || null;
}

export function writeCachedEmbyUserContext(embyGuid, context) {
	const normalizedGuid = normalizeGuid(embyGuid);
	if (!normalizedGuid) return null;

	const cache = loadCacheFile();
	const nextContext = {
		views: Array.isArray(context?.views) ? context.views : [],
		recentlyPlayed: Array.isArray(context?.recentlyPlayed) ? context.recentlyPlayed : [],
		excludedFolderLookup: context?.excludedFolderLookup || {},
		lastSyncedAt: context?.lastSyncedAt || new Date().toISOString()
	};

	cache.users ||= {};
	cache.users[normalizedGuid] = nextContext;
	saveCacheFile(cache);
	return nextContext;
}

