import JSON5 from "json5";
import { generateUUID } from "../ctaHelpers";
import ct from "countries-and-timezones";
import { Logger, LogLevel } from "../logger";
const logger = new Logger("ParseHelper", { logLevel: LogLevel.Error });
const countriesCodes = ["CN"];
export function parseArgsWithJson5(argsStr) {
    try {
        const parsed = JSON5.parse(`[${argsStr}]`);
        return Array.isArray(parsed) ? parsed : [parsed];
    }
    catch (error) {
        console.error("Failed to parse button arguments with JSON5:", argsStr, error);
        return null;
    }
}
/**
 * Get the user's country based on their time zone.
 * @param {string} userTimeZone - The user's time zone.
 * @returns {string} The user's country or the original time zone if not found.
 */
export function getCountryByTimeZone(userTimeZone) {
    const countries = ct.getAllCountries();
    for (const code in countries) {
        const country = countries[code];
        if (country.timezones.includes(userTimeZone)) {
            return country.name;
        }
    }
    logger.warn("getCountryByTimeZone: no country found for timezone:", userTimeZone);
    return userTimeZone;
}
export function validateChinaTime(userTimeZone) {
    try {
        const allZones = countriesCodes.flatMap(code => ct.getCountry(code));
        const allTimeZones = allZones.flatMap((country) => country.timezones || []);
        return allTimeZones.includes(userTimeZone);
    }
    catch (e) {
        console.error("Error validating China time for:", userTimeZone, e);
        return false;
    }
}
/**
 * Ensures a valid message DOM id exists for the current response bubble.
 *
 * Cannot mutate the caller's string variable (primitives pass by value in JS)
 * or trigger Stencil @State reactivity — so the caller must:
 *   1. Assign the returned `id` back to `this.currentDomId`
 *   2. Spread `this.messages = [...this.messages]` when `idChanged` is true
 *   3. Skip emitting events when `orphaned` is true
 *
 * @param currentId  The component's current domId (e.g. this.currentDomId)
 * @param messages   The component's messages array (objects mutated in-place for id)
 * @param prefix     ID prefix, e.g. "chatbot"
 * @returns          { id, idChanged, orphaned }
 */
export function ensureMessageId(currentId, messages, prefix = "chatbot") {
    if (currentId && currentId !== "") {
        return { id: currentId, idChanged: false, orphaned: false };
    }
    const id = `${prefix}-${generateUUID()}`;
    if (messages.length > 0) {
        // Mutate the last message's id in-place (object reference — safe across function boundary)
        messages[messages.length - 1].id = id;
        return { id, idChanged: true, orphaned: false };
    }
    logger.warn(`[ai12z-bot] event received but messages array is empty; skipping emit for domId: ${id}`);
    return { id, idChanged: true, orphaned: true };
}
