import { api } from "./client";

export type ReadingMode = "trend" | "fortune" | "heart";
export type HeavenReading = {
  id: number;
  mode: ReadingMode;
  date: string;
  subject_key: string;
  result: Record<string, any>;
  interpretation: string;
  status: "pending" | "complete" | "stopped" | "error";
  created_at: string;
};
export type HeavenSetup = {
  date: string;
  fortune: Record<string, any>;
  daily_fortune: HeavenReading | null;
  history: HeavenReading[];
};
export type HeavenStreamEvent = {
  type: "delta" | "done" | "error";
  content?: string;
  message?: string;
  cached?: boolean;
};

export const heavenApi = {
  setup(date: string): Promise<HeavenSetup> {
    return api.get(`/heaven/setup?date=${encodeURIComponent(date)}`);
  },
  trend(query: string, tradeDate: string, manual: Record<string, any> = {}): Promise<any> {
    return api.post("/heaven/trend/load", { query, trade_date: tradeDate, manual });
  },
  fortune(tradeDate: string): Promise<{ reused: boolean; reading: HeavenReading }> {
    return api.post("/heaven/fortune", { trade_date: tradeDate });
  },
  heartLine(tradeDate: string, values: number[]): Promise<any> {
    return api.post("/heaven/heart/line", { trade_date: tradeDate, values });
  },
  completeHeart(tradeDate: string, values: number[]): Promise<any> {
    return api.post("/heaven/heart/complete", {
      trade_date: tradeDate,
      values,
      first_thought_confirmed: true,
    });
  },
  readings(mode?: ReadingMode, date?: string): Promise<HeavenReading[]> {
    const query = new URLSearchParams();
    if (mode) query.set("mode", mode);
    if (date) query.set("date", date);
    return api.get(`/heaven/readings?${query}`);
  },
  remove(id: number): Promise<{ deleted: number }> {
    return api.delete(`/heaven/readings/${id}`);
  },
  interpret(
    readingId: number,
    onEvent: (event: HeavenStreamEvent) => void,
    signal?: AbortSignal,
  ): Promise<void> {
    return api.stream("/heaven/interpret", { reading_id: readingId }, onEvent, signal);
  },
};
