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

export interface GetResilienceScoreRequest {
  countryCode: string;
}

export interface GetResilienceScoreResponse {
  countryCode: string;
  overallScore: number;
  level: string;
  domains: ResilienceDomain[];
  trend: string;
  change30d: number;
  lowConfidence: boolean;
  imputationShare: number;
  baselineScore: number;
  stressScore: number;
  stressFactor: number;
  dataVersion: string;
  scoreInterval?: ScoreInterval;
  pillars: ResiliencePillar[];
  schemaVersion: string;
  headlineEligible: boolean;
}

export interface ResilienceDomain {
  id: string;
  score: number;
  weight: number;
  dimensions: ResilienceDimension[];
}

export interface ResilienceDimension {
  id: string;
  score: number;
  coverage: number;
  observedWeight: number;
  imputedWeight: number;
  imputationClass: string;
  freshness?: DimensionFreshness;
}

export interface DimensionFreshness {
  lastObservedAtMs: string;
  staleness: string;
}

export interface ScoreInterval {
  p05: number;
  p95: number;
}

export interface ResiliencePillar {
  id: string;
  score: number;
  weight: number;
  coverage: number;
  domains: ResilienceDomain[];
}

export interface GetResilienceRankingRequest {
}

export interface GetResilienceRankingResponse {
  items: ResilienceRankingItem[];
  greyedOut: ResilienceRankingItem[];
  fetchedAt: string;
  scored: number;
  total: number;
  coverage: number;
  partial: boolean;
}

export interface ResilienceRankingItem {
  countryCode: string;
  overallScore: number;
  level: string;
  lowConfidence: boolean;
  overallCoverage: number;
  rankStable: boolean;
  headlineEligible: boolean;
}

export interface GetResilienceRuntimeManifestRequest {
}

export interface GetResilienceRuntimeManifestResponse {
  manifestVersion: number;
  generatedAt: string;
  deployedCommitSha: string;
  vercelEnv: string;
  formulaTag: string;
  dataVersion: string;
  flags: ResilienceRuntimeFlag[];
  cache?: ResilienceRuntimeCacheState;
  rankingCache?: ResilienceRankingCacheState;
  constructVersions?: ResilienceRuntimeConstructVersions;
  intervals?: ResilienceRuntimeIntervalState;
}

export interface ResilienceRuntimeFlag {
  name: string;
  enabled: boolean;
}

export interface ResilienceRuntimeCacheState {
  scorePrefix: string;
  rankingKey: string;
  historyPrefix: string;
  intervalPrefix: string;
  intervalMethodology: string;
}

export interface ResilienceRankingCacheState {
  fetchedAt: string;
  count: number;
  scored: number;
  total: number;
}

export interface ResilienceRuntimeConstructVersions {
  energy: string;
}

export interface ResilienceRuntimeIntervalState {
  available: boolean;
  methodology: string;
  sampleCountry: string;
  lastObservedAt: 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 ResilienceServiceClientOptions {
  fetch?: typeof fetch;
  defaultHeaders?: Record<string, string>;
}

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

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

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

  async getResilienceScore(req: GetResilienceScoreRequest, options?: ResilienceServiceCallOptions): Promise<GetResilienceScoreResponse> {
    let path = "/api/resilience/v1/get-resilience-score";
    const params = new URLSearchParams();
    if (req.countryCode != null && req.countryCode !== "") params.set("countryCode", String(req.countryCode));
    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 GetResilienceScoreResponse;
  }

  async getResilienceRanking(_req: GetResilienceRankingRequest, options?: ResilienceServiceCallOptions): Promise<GetResilienceRankingResponse> {
    let path = "/api/resilience/v1/get-resilience-ranking";
    const url = this.baseURL + path;

    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 GetResilienceRankingResponse;
  }

  async getResilienceRuntimeManifest(_req: GetResilienceRuntimeManifestRequest, options?: ResilienceServiceCallOptions): Promise<GetResilienceRuntimeManifestResponse> {
    let path = "/api/resilience/v1/get-runtime-manifest";
    const url = this.baseURL + path;

    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 GetResilienceRuntimeManifestResponse;
  }

  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);
  }
}

