import ModelClient, { isUnexpected } from "@azure-rest/ai-inference";
import { AzureKeyCredential } from "@azure/core-auth";

const KEY = process.env.NEIS_API_KEY;

export function removeNutritionInfo(value: string): string {
    const lines = value.trim().split('\n');
    const cleanedLines = lines.map(line => line.replace(/\(.*?\)/g, '').trim());
    const result = cleanedLines.join('\n');
    return result;
}

export async function getMealInfo(MLSV_YMD: string): Promise<{ meal: string; date: string, kcal: string }> {
    const url = `https://open.neis.go.kr/hub/mealServiceDietInfo?Type=json&ATPT_OFCDC_SC_CODE=E10&SD_SCHUL_CODE=7331071&MLSV_YMD=${MLSV_YMD}&KEY=${KEY}`;
    const response = await fetch(url);
    const data = await response.json();
    // @ts-ignore
    const DDISH_NM = data.mealServiceDietInfo[1].row[0].DDISH_NM;
    return {
        meal: removeNutritionInfo(DDISH_NM.replace(/<br\s*\/?>/gi, '\n')),
        date: MLSV_YMD,
        // @ts-ignore

        kcal: data.mealServiceDietInfo[1].row[0].CAL_INFO,
    };
    
}

export async function NameToEmoji(name: string): Promise<string> {
    const token = process.env.GITHUB_TOKEN;
    if (!token) {
        throw new Error("GITHUB_TOKEN environment variable is not set.");
    }
    const endpoint = "https://models.github.ai/inference";
    const model = "openai/gpt-4.1";

    const client = ModelClient(
        endpoint,
        new AzureKeyCredential(token),
    );
    
    const systemPrompt = `You are an emoji responder.
When given any word or phrase, you must reply with exactly one emoji per item, matching the meaning as closely as possible.
**If multiple words or phrases are given, they will be separated by commas (,), and your emojis must also be separated by commas (,) in the same order.**
Do not include any words, explanations, or multiple emojis—just **one emoji per item**.

Examples:
Q: 현미찹쌀밥
A: 🍚
Q: 개
A: 🐶
Q: 축구
A: ⚽
Q: 해넘이
A: 🌇
Q: 현미찹쌀밥,개,축구
A: 🍚,🐶,⚽
`;

    const response = await client.path("/chat/completions").post({
        body: {
            messages: [
                { role: "system", content: systemPrompt },
                { role: "user", content: name }
            ],
            temperature: 1.0,
            top_p: 1.0,
            model: model
        }
    });
    if (isUnexpected(response)) {
        throw response.body.error;
    }

    const choices = response.body?.choices;
    if (!choices || !choices[0]?.message?.content) {
        throw new Error("No valid response from the model.");
    }
    return choices[0].message.content as string;
}