import assert from "assert";
import { $, MD5 } from "bun";
import { createWriteStream, existsSync, rmSync, writeFileSync } from "fs";

export type CiderNowPlaying = {
	status: string;
	info: {
		albumName: string;
		artistName: string;
		artwork: {
			bgColor: string;
			hasP3: boolean;
			height: number;
			textColor1: string;
			textColor2: string;
			textColor3: string;
			textColor4: string;
			url: string;
			width: number;
			[key: string]: any; // allow any other properties
		};
		contentRating: string;
		discNumber: number;
		durationInMillis: number;
		genreNames: string[];
		hasLyrics: boolean;
		name: string;
		playParams: {
			catalogId: string;
			id: string;
			isLibrary: boolean;
			kind: string;
			reporting: boolean;
			reportingId: string;
			[key: string]: any;
		};
		releaseDate: string;
		trackNumber: number;
		composerName: string;
		isrc: string;
		previews: any[]; // empty objects or unknown preview data
		currentPlaybackTime: number;
		remainingTime: number;
		inFavorites: boolean;
		inLibrary: boolean;
		shuffleMode: number;
		repeatMode: number;
		[key: string]: any;
	};
	[key: string]: any;
};

// cachedAlbumArt = /tmp/.ocbwoy3-ciderv2lib-md5(isrc+albumName).jpg

export type albumStuffF = {
	artist: string;
	album: string;
	song: string;
	artUrl?: string;
};

export const albumRewriteRegexes: { a: RegExp; b: string | false }[] = [
	{
		a: / \(Original( (Video )?Game)? Soundtrack.*\)$/i,
		b: "",
	},
	{
		a: / - Single$/i,
		b: false,
	},
	{
		a: / Soundtrack$/i,
		b: "",
	},
	{
		a: /^(DELTARUNE|Deltarune) (chapter|chapters) /i,
		b: "Deltarune $2 ",
	},
	{
		a: / - EP$/i,
		b: "",
	},
	{
		a: /^regretevator$/i,
		b: false,
	},
];

export function doRewritesRn(t: string) {
	let m = t;
	for (const x of albumRewriteRegexes) {
		if (x.a.test(m)) {
			if (x.b === false) return "";
			m = m.replace(x.a, x.b);
		}
	}
	return m;
}

export async function fetchAlbumStuff(): Promise<albumStuffF> {
	const d = await fetch(
		"http://localhost:10767/api/v1/playback/now-playing?token=z",
	);
	// console.log(d.status, d.statusText, await d.text())
	const { info }: CiderNowPlaying = await d.json();
	const special = MD5.hash(info.isrc + info.albumName, "hex");
	const path = `/tmp/.ocbwoy3-ciderv2lib-md5-${special}.jpg`;

	// console.log(existsSync(path), `hyprctl dispatch exec ${`wget -q --unlink -O ${path} ${info.artwork.url}`}`);

	if (!existsSync(path)) {
		writeFileSync(path, "");
		try {
			const ct = await fetch(info.artwork.url);
			assert(ct.ok);
			const data = Buffer.from(await ct.arrayBuffer());
			writeFileSync(path, data);
			// writeFileSync(path,await ct.body?.pipeTo)
		} catch {
			rmSync(path);
		}
	}
	return {
		artist: info.artistName,
		album: doRewritesRn(info.albumName),
		song: info.name,
		artUrl: existsSync(path) ? path : undefined,
	};
}

// await fetchAlbumStuff();
