import dotenv from 'dotenv';
import { readFileSync } from 'fs';
import { join } from 'path';

dotenv.config();

let _raspberryHost = process.env.RASPBERRY_PI_HOST ?? 'http://raspberrypi.local';
let _raspberryPort = Number(process.env.RASPBERRY_PI_PORT) || 8000;
let _token = process.env.QUIBOT_TOKEN ?? 'MY_SECRET_TOKEN';
const APP_PORT = Number(process.env.PORT) || 5000;
const piperUrl = process.env.PIPER_URL ?? '';
const mcpUrl = process.env.MCP_URL ?? '';
const llamacppUrl = process.env.LLAMA_CPP_URL ?? '';
const llamacppApiKey = process.env.LLAMA_API_KEY ?? '';
const llamaPreambleRaw = process.env.LLAMA_PREAMBLE ?? '';
const llamacppPreamble = llamaPreambleRaw.endsWith('.md')
  ? readFileSync(llamaPreambleRaw, 'utf-8')
  : llamaPreambleRaw;

export const getRaspberryHost = () => _raspberryHost;
export const getRaspberryPort = () => _raspberryPort;
export const getToken = () => _token;

export function setRaspberryHost(host: string) {
  _raspberryHost = host;
}

export function setRaspberryPort(port: number) {
  _raspberryPort = port;
}

export function setToken(token: string) {
  _token = token;
}

export const getConfig = () => ({
  raspberryPi: {
    host: getRaspberryHost(),
    port: getRaspberryPort(),
  },
  token: getToken(),
});

export const getLlamacppUrl = () => llamacppUrl;
export const getLlamacppApiKey = () => llamacppApiKey;
export const getLlamacppPreamble = () => llamacppPreamble;

export const getPiperUrl = () => piperUrl;
export const getPiperModelDir = () =>
  process.env.PIPER_MODELS_DIR || join('/tmp', 'quibot-piper-models');
export const getPiperModel = () =>
  process.env.PIPER_MODEL ||
  join(getPiperModelDir(), 'ca_ES-upc_ona-medium.onnx');
export const getMcpUrl = () => mcpUrl;

export const getAppPort = () => APP_PORT;
