// @ts-nocheck
// Code generated by protoc-gen-ts-client. DO NOT EDIT.
// source: worldmonitor/forecast/v1/service.proto

export interface GetForecastsRequest {
  domain: string;
  region: string;
}

export interface GetForecastsResponse {
  forecasts: Forecast[];
  generatedAt: number;
}

export interface Forecast {
  id: string;
  domain: string;
  region: string;
  title: string;
  scenario: string;
  feedSummary: string;
  probability: number;
  confidence: number;
  timeHorizon: string;
  signals: ForecastSignal[];
  cascades: CascadeEffect[];
  trend: string;
  priorProbability: number;
  calibration?: CalibrationInfo;
  createdAt: number;
  updatedAt: number;
  perspectives?: Perspectives;
  projections?: Projections;
  caseFile?: ForecastCase;
  simulationAdjustment: number;
  simPathConfidence: number;
  demotedBySimulation: boolean;
}

export interface ForecastSignal {
  type: string;
  value: string;
  weight: number;
}

export interface CascadeEffect {
  domain: string;
  effect: string;
  probability: number;
}

export interface CalibrationInfo {
  marketTitle: string;
  marketPrice: number;
  drift: number;
  source: string;
}

export interface Perspectives {
  strategic: string;
  regional: string;
  contrarian: string;
}

export interface Projections {
  h24: number;
  d7: number;
  d30: number;
}

export interface ForecastCase {
  supportingEvidence: ForecastCaseEvidence[];
  counterEvidence: ForecastCaseEvidence[];
  triggers: string[];
  actorLenses: string[];
  baseCase: string;
  escalatoryCase: string;
  contrarianCase: string;
  changeSummary: string;
  changeItems: string[];
  actors: ForecastActor[];
  worldState?: ForecastWorldState;
  branches: ForecastBranch[];
}

export interface ForecastCaseEvidence {
  type: string;
  summary: string;
  weight: number;
}

export interface ForecastActor {
  id: string;
  name: string;
  category: string;
  role: string;
  objectives: string[];
  constraints: string[];
  likelyActions: string[];
  influenceScore: number;
}

export interface ForecastWorldState {
  summary: string;
  activePressures: string[];
  stabilizers: string[];
  keyUnknowns: string[];
}

export interface ForecastBranch {
  kind: string;
  title: string;
  summary: string;
  outcome: string;
  projectedProbability: number;
  rounds: ForecastBranchRound[];
}

export interface ForecastBranchRound {
  round: number;
  focus: string;
  developments: string[];
  actorMoves: string[];
  probabilityShift: number;
}

export interface GetSimulationPackageRequest {
  runId: string;
}

export interface GetSimulationPackageResponse {
  found: boolean;
  runId: string;
  pkgKey: string;
  schemaVersion: string;
  theaterCount: number;
  generatedAt: number;
  note: string;
  error: string;
}

export interface GetSimulationOutcomeRequest {
  runId: string;
}

export interface GetSimulationOutcomeResponse {
  found: boolean;
  runId: string;
  outcomeKey: string;
  schemaVersion: string;
  theaterCount: number;
  generatedAt: number;
  note: string;
  error: string;
  theaterSummariesJson: string;
}

export interface FieldViolation {
  field: string;
  description: string;
}

export class ValidationError extends Error {
  violations: FieldViolation[];

  constructor(violations: FieldViolation[]) {
    super("Validation failed");
    this.name = "ValidationError";
    this.violations = violations;
  }
}

export class ApiError extends Error {
  statusCode: number;
  body: string;

  constructor(statusCode: number, message: string, body: string) {
    super(message);
    this.name = "ApiError";
    this.statusCode = statusCode;
    this.body = body;
  }
}

export interface ForecastServiceClientOptions {
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
}

export interface ForecastServiceCallOptions {
  headers?: Record<string, string>;
  signal?: AbortSignal;
}

export class ForecastServiceClient {
  private baseURL: string;
  private fetchFn: typeof fetch;
  private defaultHeaders: Record<string, string>;

  constructor(baseURL: string, options?: ForecastServiceClientOptions) {
    this.baseURL = baseURL.replace(/\/+$/, "");
    this.fetchFn = options?.fetch ?? globalThis.fetch;
    this.defaultHeaders = { ...options?.defaultHeaders };
  }

  async getForecasts(req: GetForecastsRequest, options?: ForecastServiceCallOptions): Promise<GetForecastsResponse> {
    let path = "/api/forecast/v1/get-forecasts";
    const params = new URLSearchParams();
    if (req.domain != null && req.domain !== "") params.set("domain", String(req.domain));
    if (req.region != null && req.region !== "") params.set("region", String(req.region));
    const url = this.baseURL + path + (params.toString() ? "?" + params.toString() : "");

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "GET",
      headers,
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as GetForecastsResponse;
  }

  async getSimulationPackage(req: GetSimulationPackageRequest, options?: ForecastServiceCallOptions): Promise<GetSimulationPackageResponse> {
    let path = "/api/forecast/v1/get-simulation-package";
    const params = new URLSearchParams();
    if (req.runId != null && req.runId !== "") params.set("runId", String(req.runId));
    const url = this.baseURL + path + (params.toString() ? "?" + params.toString() : "");

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "GET",
      headers,
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as GetSimulationPackageResponse;
  }

  async getSimulationOutcome(req: GetSimulationOutcomeRequest, options?: ForecastServiceCallOptions): Promise<GetSimulationOutcomeResponse> {
    let path = "/api/forecast/v1/get-simulation-outcome";
    const params = new URLSearchParams();
    if (req.runId != null && req.runId !== "") params.set("runId", String(req.runId));
    const url = this.baseURL + path + (params.toString() ? "?" + params.toString() : "");

    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      ...this.defaultHeaders,
      ...options?.headers,
    };

    const resp = await this.fetchFn(url, {
      method: "GET",
      headers,
      signal: options?.signal,
    });

    if (!resp.ok) {
      return this.handleError(resp);
    }

    return await resp.json() as GetSimulationOutcomeResponse;
  }

  private async handleError(resp: Response): Promise<never> {
    const body = await resp.text();
    if (resp.status === 400) {
      try {
        const parsed = JSON.parse(body);
        if (parsed.violations) {
          throw new ValidationError(parsed.violations);
        }
      } catch (e) {
        if (e instanceof ValidationError) throw e;
      }
    }
    throw new ApiError(resp.status, `Request failed with status ${resp.status}`, body);
  }
}

