import path from "path";

export const BACKEND_ROOT = path.resolve(__dirname, "..");
export const MODULE_ROOT = path.resolve(BACKEND_ROOT, "..");

function toBooleanFlag(value: string | undefined, defaultValue: boolean): boolean {
  if (!value || value.trim() === "") {
    return defaultValue;
  }
  const lowered = value.trim().toLowerCase();
  return !(lowered === "0" || lowered === "false" || lowered === "off" || lowered === "no");
}

export const PORT = Number(process.env.PORT ?? 8787);
export const TIMEZONE = process.env.TZ_FALLBACK ?? "Europe/Moscow";
export const DEFAULT_OPENAI_BASE_URL = process.env.OPENAI_BASE_URL ?? "https://api.openai.com/v1";
export const DEFAULT_MODEL = process.env.OPENAI_MODEL ?? "gpt-4o-mini";
export const DEFAULT_TEMPERATURE = Number(process.env.OPENAI_TEMPERATURE ?? 0);
export const DEFAULT_MAX_OUTPUT_TOKENS = Number(process.env.OPENAI_MAX_OUTPUT_TOKENS ?? 700);
export const DEFAULT_PROMPT_VERSION = process.env.DEFAULT_PROMPT_VERSION ?? "normalizer_v2_0_2";
export const FEATURE_ASSISTANT_INVESTIGATION_STATE_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_INVESTIGATION_STATE_V1,
  true
);
export const FEATURE_ASSISTANT_CONTRACTS_V11 = toBooleanFlag(process.env.FEATURE_ASSISTANT_CONTRACTS_V11, true);
export const FEATURE_ASSISTANT_STATE_FOLLOWUP_BINDING_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_STATE_FOLLOWUP_BINDING_V1,
  true
);
export const FEATURE_ASSISTANT_EVIDENCE_ENRICHMENT_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_EVIDENCE_ENRICHMENT_V1,
  true
);
export const FEATURE_ASSISTANT_BROAD_GUARD_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_BROAD_GUARD_V1,
  true
);
export const FEATURE_ASSISTANT_MIN_EVIDENCE_GATE_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_MIN_EVIDENCE_GATE_V1,
  true
);
export const FEATURE_ASSISTANT_ANTI_GENERIC_RANKING_GUARD_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_ANTI_GENERIC_RANKING_GUARD_V1,
  true
);
export const FEATURE_ASSISTANT_ANSWER_POLICY_V11 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_ANSWER_POLICY_V11,
  false
);
export const FEATURE_ASSISTANT_ACCOUNTANT_EVAL_V1 = toBooleanFlag(
  process.env.FEATURE_ASSISTANT_ACCOUNTANT_EVAL_V1,
  true
);

export const DATA_DIR = process.env.DATA_DIR ?? path.resolve(MODULE_ROOT, "data");
export const TRACES_DIR = path.resolve(DATA_DIR, "traces");
export const PRESETS_DIR = path.resolve(DATA_DIR, "presets");
export const EVAL_CASES_DIR = path.resolve(DATA_DIR, "eval_cases");
export const ASSISTANT_SESSIONS_DIR = path.resolve(DATA_DIR, "assistant_sessions");

export const PROMPTS_DIR = path.resolve(MODULE_ROOT, "prompts");
export const REPORTS_DIR = path.resolve(MODULE_ROOT, "reports");
export const EVAL_DATASETS_DIR = path.resolve(MODULE_ROOT, "eval_cases");
export const SCHEMAS_DIR = path.resolve(BACKEND_ROOT, "src", "schemas");
export const ARCH_EXPORT_2020_DIR = path.resolve(MODULE_ROOT, "..", "docs", "ARCH", "2020экспорт");
