// Code generated by protoc-gen-ts-server. 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 ServerContext {
  request: Request;
  pathParams: Record<string, string>;
  headers: Record<string, string>;
}

export interface ServerOptions {
  onError?: (error: unknown, req: Request) => Response | Promise<Response>;
  validateRequest?: (methodName: string, body: unknown) => FieldViolation[] | undefined;
}

export interface RouteDescriptor {
  method: string;
  path: string;
  handler: (req: Request) => Promise<Response>;
}

export interface ResilienceServiceHandler {
  getResilienceScore(ctx: ServerContext, req: GetResilienceScoreRequest): Promise<GetResilienceScoreResponse>;
  getResilienceRanking(ctx: ServerContext, req: GetResilienceRankingRequest): Promise<GetResilienceRankingResponse>;
  getResilienceRuntimeManifest(ctx: ServerContext, req: GetResilienceRuntimeManifestRequest): Promise<GetResilienceRuntimeManifestResponse>;
}

export function createResilienceServiceRoutes(
  handler: ResilienceServiceHandler,
  options?: ServerOptions,
): RouteDescriptor[] {
  return [
    {
      method: "GET",
      path: "/api/resilience/v1/get-resilience-score",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const url = new URL(req.url, "http://localhost");
          const params = url.searchParams;
          const body: GetResilienceScoreRequest = {
            countryCode: params.get("countryCode") ?? "",
          };
          if (options?.validateRequest) {
            const bodyViolations = options.validateRequest("getResilienceScore", body);
            if (bodyViolations) {
              throw new ValidationError(bodyViolations);
            }
          }

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getResilienceScore(ctx, body);
          return new Response(JSON.stringify(result as GetResilienceScoreResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/resilience/v1/get-resilience-ranking",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as GetResilienceRankingRequest;

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getResilienceRanking(ctx, body);
          return new Response(JSON.stringify(result as GetResilienceRankingResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
    {
      method: "GET",
      path: "/api/resilience/v1/get-runtime-manifest",
      handler: async (req: Request): Promise<Response> => {
        try {
          const pathParams: Record<string, string> = {};
          const body = {} as GetResilienceRuntimeManifestRequest;

          const ctx: ServerContext = {
            request: req,
            pathParams,
            headers: Object.fromEntries(req.headers.entries()),
          };

          const result = await handler.getResilienceRuntimeManifest(ctx, body);
          return new Response(JSON.stringify(result as GetResilienceRuntimeManifestResponse), {
            status: 200,
            headers: { "Content-Type": "application/json" },
          });
        } catch (err: unknown) {
          if (err instanceof ValidationError) {
            return new Response(JSON.stringify({ violations: err.violations }), {
              status: 400,
              headers: { "Content-Type": "application/json" },
            });
          }
          if (options?.onError) {
            return options.onError(err, req);
          }
          const message = err instanceof Error ? err.message : String(err);
          return new Response(JSON.stringify({ message }), {
            status: 500,
            headers: { "Content-Type": "application/json" },
          });
        }
      },
    },
  ];
}

