import { DependencyContainer } from "tsyringe";
import { IPostDBLoadMod } from "@spt/models/external/IPostDBLoadMod";
import { DatabaseServer } from "@spt/servers/DatabaseServer";
import { ILogger } from "@spt/models/spt/utils/ILogger";
import { ItemMap } from "./references/items";
import * as fs from "fs";
import * as path from "path";

class TarkovHDItemRework implements IPostDBLoadMod {
    public postDBLoad(container: DependencyContainer): void {
        const logger = container.resolve<ILogger>("WinstonLogger");

        try {
            // Resolve DatabaseServer and retrieve tables
            const dbServer = container.resolve<DatabaseServer>("DatabaseServer");
            const tables = dbServer.getTables();

            if (!tables || !tables.templates || !tables.templates.items) {
                throw new Error("Database tables or 'items' are undefined. Verify DatabaseServer is fully loaded.");
            }

            const items = tables.templates.items;

            // Load assetReplacements.json
            const assetReplacementsPath = path.resolve(__dirname, "../db/assetReplacements.json");
            const jsonData = fs.readFileSync(assetReplacementsPath, "utf8");
            const assetReplacements: Record<string, string> = JSON.parse(jsonData);

            // Iterate through asset replacements and modify database entries
            for (const [humanReadableKey, customBundlePath] of Object.entries(assetReplacements)) {
                const itemID = ItemMap[humanReadableKey]; // Lookup the item ID from ItemMap

                if (itemID && items[itemID]) {
                    const resolvedBundlePath = customBundlePath;
                    items[itemID]._props.Prefab.path = resolvedBundlePath;
                    logger.success(`Replaced asset bundle for ${humanReadableKey} (${itemID})`);
                } else {
                    logger.error(`Item ${humanReadableKey} not found or invalid in ItemMap.`);
                }
            }
        } catch (error) {
            logger.error(`Critical error in TarkovHDItemRework: ${error.message}`);
        }
    }
}

export const mod = new TarkovHDItemRework();
