import { Type, type Static } from "@sinclair/typebox";

const isoTimestampPattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(?:\\.[0-9]{3})?Z$";
const modelIdPattern = "^[a-z0-9][a-z0-9.-]+$";
const safeReferencePattern = "^[A-Za-z0-9][A-Za-z0-9:._-]{0,159}$";
const uuidPattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$";

export const AdminGenerationRecordSchema = Type.Object(
  {
    generation_id: Type.String({ pattern: uuidPattern }),
    owner_ref: Type.String({ pattern: uuidPattern }),
    project_id: Type.String({ pattern: uuidPattern }),
    model_id: Type.String({ maxLength: 80, pattern: modelIdPattern }),
    ratio: Type.Union([Type.Literal("3:4"), Type.Literal("1:1"), Type.Literal("4:3"), Type.Literal("9:16")]),
    status: Type.Union([Type.Literal("queued"), Type.Literal("running"), Type.Literal("succeeded"), Type.Literal("failed"), Type.Literal("rejected")]),
    created_at: Type.String({ pattern: isoTimestampPattern }),
    completed_at: Type.Union([Type.String({ pattern: isoTimestampPattern }), Type.Null()]),
    duration_ms: Type.Union([Type.Integer({ minimum: 0 }), Type.Null()]),
    confirmed_credit_cost: Type.Integer({ minimum: 0 }),
    reserved_credits: Type.Integer({ minimum: 0 }),
    final_credit_state: Type.Union([Type.Literal("committed"), Type.Literal("released"), Type.Null()]),
    error_category: Type.Union([
      Type.Literal("upstream_timeout"), Type.Literal("upstream_failed"), Type.Literal("safety_rejected"),
      Type.Literal("model_disabled"), Type.Literal("gateway_balance_insufficient"), Type.Literal("gateway_contract_invalid"),
      Type.Literal("reference_invalid"), Type.Literal("unknown_retryable"), Type.Literal("unknown_non_retryable"), Type.Null(),
    ]),
  },
  { additionalProperties: false, $id: "AdminGenerationRecord" },
);

export const AdminGenerationListResponseSchema = Type.Object(
  {
    generated_at: Type.String({ pattern: isoTimestampPattern }),
    items: Type.Array(Type.Ref(AdminGenerationRecordSchema), { maxItems: 100 }),
  },
  { additionalProperties: false, $id: "AdminGenerationListResponse" },
);

export const PrivateContentNoticeAckRequestSchema = Type.Object(
  { expected_notice_version: Type.String({ minLength: 1, maxLength: 80, pattern: "^[A-Za-z0-9_.:-]+$" }) },
  { additionalProperties: false, $id: "PrivateContentNoticeAckRequest" },
);

export const PrivateContentNoticeAckResponseSchema = Type.Object(
  {
    notice_version: Type.String({ minLength: 1, maxLength: 80, pattern: "^[A-Za-z0-9_.:-]+$" }),
    acknowledged_at: Type.String({ pattern: isoTimestampPattern }),
    status: Type.Literal("acknowledged"),
  },
  { additionalProperties: false, $id: "PrivateContentNoticeAckResponse" },
);

export const PrivateContentPromptResponseSchema = Type.Object(
  {
    generation_id: Type.String({ pattern: uuidPattern }),
    content_type: Type.Literal("prompt"),
    prompt: Type.String({ minLength: 1, maxLength: 4000 }),
  },
  { additionalProperties: false, $id: "PrivateContentPromptResponse" },
);

export const PrivateContentGenerationParamsSchema = Type.Object(
  { generationId: Type.String({ pattern: uuidPattern }) },
  { additionalProperties: false, $id: "PrivateContentGenerationParams" },
);

export type AdminGenerationRecord = Static<typeof AdminGenerationRecordSchema>;
export type AdminGenerationListResponse = Static<typeof AdminGenerationListResponseSchema>;
export type PrivateContentNoticeAckRequest = Static<typeof PrivateContentNoticeAckRequestSchema>;
export type PrivateContentNoticeAckResponse = Static<typeof PrivateContentNoticeAckResponseSchema>;
export type PrivateContentPromptResponse = Static<typeof PrivateContentPromptResponseSchema>;

export const AdminAuditQuerySchema = Type.Object(
  {
    cursor: Type.Optional(Type.String({ maxLength: 512, pattern: "^[A-Za-z0-9_-]+$" })),
    limit: Type.Optional(Type.Integer({ maximum: 100, minimum: 1 })),
  },
  { additionalProperties: false, $id: "AdminAuditQuery" },
);

export const AdminOperationAuditItemSchema = Type.Object(
  {
    actor_ref: Type.String({ pattern: safeReferencePattern }),
    actor_type: Type.Union([Type.Literal("system"), Type.Literal("super_admin")]),
    after_summary: Type.Union([Type.String({ maxLength: 2048 }), Type.Null()]),
    before_summary: Type.Union([Type.String({ maxLength: 2048 }), Type.Null()]),
    expires_at: Type.String({ pattern: isoTimestampPattern }),
    log_id: Type.String({ pattern: uuidPattern }),
    occurred_at: Type.String({ pattern: isoTimestampPattern }),
    operation_type: Type.String({ maxLength: 160, pattern: safeReferencePattern }),
    result: Type.Union([Type.Literal("succeeded"), Type.Literal("failed")]),
    target_ref: Type.String({ pattern: safeReferencePattern }),
    target_type: Type.String({ maxLength: 160, pattern: safeReferencePattern }),
  },
  { additionalProperties: false, $id: "AdminOperationAuditItem" },
);

export const AdminOperationAuditResponseSchema = Type.Object(
  {
    generated_at: Type.String({ pattern: isoTimestampPattern }),
    items: Type.Array(Type.Ref(AdminOperationAuditItemSchema), { maxItems: 100 }),
    next_cursor: Type.Union([Type.String({ maxLength: 512, pattern: "^[A-Za-z0-9_-]+$" }), Type.Null()]),
  },
  { additionalProperties: false, $id: "AdminOperationAuditResponse" },
);

export const PrivateContentAccessAuditItemSchema = Type.Object(
  {
    actor_ref: Type.String({ pattern: safeReferencePattern }),
    content_type: Type.Union([Type.Literal("image"), Type.Literal("prompt")]),
    expires_at: Type.String({ pattern: isoTimestampPattern }),
    log_id: Type.String({ pattern: uuidPattern }),
    occurred_at: Type.String({ pattern: isoTimestampPattern }),
    target_ref: Type.String({ pattern: safeReferencePattern }),
  },
  { additionalProperties: false, $id: "PrivateContentAccessAuditItem" },
);

export const PrivateContentAccessAuditResponseSchema = Type.Object(
  {
    generated_at: Type.String({ pattern: isoTimestampPattern }),
    items: Type.Array(Type.Ref(PrivateContentAccessAuditItemSchema), { maxItems: 100 }),
    next_cursor: Type.Union([Type.String({ maxLength: 512, pattern: "^[A-Za-z0-9_-]+$" }), Type.Null()]),
  },
  { additionalProperties: false, $id: "PrivateContentAccessAuditResponse" },
);

export type AdminAuditQuery = Static<typeof AdminAuditQuerySchema>;
export type AdminOperationAuditItem = Static<typeof AdminOperationAuditItemSchema>;
export type AdminOperationAuditResponse = Static<typeof AdminOperationAuditResponseSchema>;
export type PrivateContentAccessAuditItem = Static<typeof PrivateContentAccessAuditItemSchema>;
export type PrivateContentAccessAuditResponse = Static<typeof PrivateContentAccessAuditResponseSchema>;

export const AdminOverviewResponseSchema = Type.Object(
  {
    generated_at: Type.String({ pattern: isoTimestampPattern }),
    user_slots: Type.Object(
      {
        active_and_suspended: Type.Integer({ minimum: 0 }),
        limit: Type.Integer({ minimum: 1 }),
      },
      { additionalProperties: false },
    ),
    generation_jobs: Type.Object(
      {
        pending_manual_review: Type.Integer({ minimum: 0 }),
        pending_manual_review_oldest_at: Type.Union([Type.String({ pattern: isoTimestampPattern }), Type.Null()]),
        queued: Type.Integer({ minimum: 0 }),
        running: Type.Integer({ minimum: 0 }),
      },
      { additionalProperties: false },
    ),
    models: Type.Object(
      {
        configured_default_model_id: Type.Union([Type.String({ maxLength: 80, pattern: modelIdPattern }), Type.Null()]),
        configured_model_count: Type.Integer({ minimum: 0 }),
        recommended_model_id: Type.Union([Type.String({ maxLength: 80, pattern: modelIdPattern }), Type.Null()]),
        runtime_available_count: Type.Integer({ minimum: 0 }),
      },
      { additionalProperties: false },
    ),
    storage: Type.Object(
      {
        last_measured_at: Type.Union([Type.String({ pattern: isoTimestampPattern }), Type.Null()]),
        limit_bytes: Type.Integer({ minimum: 1 }),
        managed_content_bytes: Type.Integer({ minimum: 0 }),
        status: Type.Union([
          Type.Literal("normal"),
          Type.Literal("critical"),
          Type.Literal("full"),
          Type.Literal("unavailable"),
        ]),
      },
      { additionalProperties: false },
    ),
    services: Type.Array(
      Type.Object(
        {
          checked_at: Type.Union([Type.String({ pattern: isoTimestampPattern }), Type.Null()]),
          service_id: Type.Union([
            Type.Literal("resend"),
            Type.Literal("amap"),
            Type.Literal("ai_gateway"),
            Type.Literal("worker"),
            Type.Literal("asset_root"),
          ]),
          status: Type.Union([
            Type.Literal("available"),
            Type.Literal("degraded"),
            Type.Literal("paused"),
            Type.Literal("unavailable"),
          ]),
        },
        { additionalProperties: false },
      ),
      { maxItems: 5 },
    ),
    recent_operations: Type.Array(
      Type.Object(
        {
          created_at: Type.String({ pattern: isoTimestampPattern }),
          operation_id: Type.String({ pattern: "^[0-9a-fA-F-]{36}$" }),
          operation_type: Type.String({ maxLength: 80, pattern: "^[a-z][a-z0-9_]+$" }),
          result: Type.Union([Type.Literal("succeeded"), Type.Literal("rejected"), Type.Literal("failed")]),
          target_ref: Type.String({ pattern: safeReferencePattern }),
        },
        { additionalProperties: false },
      ),
      { maxItems: 10 },
    ),
    asset_cleanup: Type.Object(
      {
        pending_jobs: Type.Integer({ minimum: 0 }),
      },
      { additionalProperties: false },
    ),
  },
  { additionalProperties: false, $id: "AdminOverviewResponse" },
);

export type AdminOverviewResponse = Static<typeof AdminOverviewResponseSchema>;

const adminServiceStatusSchema = Type.Union([
  Type.Literal("active"),
  Type.Literal("paused_quota"),
  Type.Literal("paused_provider"),
  Type.Literal("disabled"),
  Type.Literal("degraded"),
  Type.Literal("unavailable"),
]);

const adminServiceIdSchema = Type.Union([
  Type.Literal("resend"),
  Type.Literal("amap"),
  Type.Literal("ai_gateway"),
  Type.Literal("worker"),
  Type.Literal("api"),
  Type.Literal("asset_root"),
]);

export const AdminServicesStorageResponseSchema = Type.Object({
  generated_at: Type.String({ pattern: isoTimestampPattern }),
  services: Type.Array(Type.Object({
    checked_at: Type.Union([Type.String({ pattern: isoTimestampPattern }), Type.Null()]),
    configured: Type.Boolean(),
    impact_scope: Type.Union([
      Type.Literal("none"),
      Type.Literal("authentication"),
      Type.Literal("location"),
      Type.Literal("generation"),
      Type.Literal("storage"),
      Type.Literal("api"),
      Type.Literal("model"),
      Type.Literal("account"),
      Type.Literal("unknown"),
    ]),
    pause_reason: Type.Union([Type.String({ maxLength: 80, pattern: "^[a-z][a-z0-9_]*$" }), Type.Null()]),
    service_id: adminServiceIdSchema,
    status: adminServiceStatusSchema,
  }, { additionalProperties: false }), { minItems: 6, maxItems: 6 }),
  storage: Type.Object({
    capacity_notice_level: Type.Union([Type.Literal("normal"), Type.Literal("warning"), Type.Literal("critical")]),
    cleanup_pending_count: Type.Integer({ minimum: 0 }),
    data_root_ref: Type.Literal("configured_local_data_root"),
    hard_limit_bytes: Type.Integer({ minimum: 1 }),
    last_measured_at: Type.Union([Type.String({ pattern: isoTimestampPattern }), Type.Null()]),
    managed_content_bytes: Type.Integer({ minimum: 0 }),
    remeasurement_required: Type.Boolean(),
    status: Type.Union([Type.Literal("active"), Type.Literal("full"), Type.Literal("unavailable")]),
    storage_backend: Type.Literal("local_filesystem"),
  }, { additionalProperties: false }),
}, { additionalProperties: false, $id: "AdminServicesStorageResponse" });

export const AdminDiagnosticsResponseSchema = Type.Object({
  generated_at: Type.String({ pattern: isoTimestampPattern }),
  diagnostic_text: Type.String({ minLength: 1, maxLength: 12_000 }),
  services: Type.Ref(AdminServicesStorageResponseSchema),
  system: Type.Object({
    api_status: Type.Union([Type.Literal("ready"), Type.Literal("degraded"), Type.Literal("unavailable")]),
    app_version: Type.String({ maxLength: 80, pattern: "^[A-Za-z0-9][A-Za-z0-9._-]*$" }),
    browser_support: Type.Array(Type.Object({
      brand: Type.Union([Type.Literal("Google Chrome"), Type.Literal("Microsoft Edge")]),
      major: Type.Integer({ minimum: 1 }),
    }, { additionalProperties: false }), { maxItems: 2 }),
    worker_status: Type.Union([Type.Literal("ready"), Type.Literal("degraded"), Type.Literal("unavailable")]),
  }, { additionalProperties: false }),
}, { additionalProperties: false, $id: "AdminDiagnosticsResponse" });

export type AdminServicesStorageResponse = Static<typeof AdminServicesStorageResponseSchema>;
export type AdminDiagnosticsResponse = Static<typeof AdminDiagnosticsResponseSchema>;
