export type QueuePriority = 0 | 1 | 2 | 3;
export type FilterMode = "collapse" | "hide";

export interface SiteDefinition {
  id: string;
  name: string;
  urlPatterns: string[];
  requiredSelectors: string[];
  post: {
    rootSelectors: string[];
    textSelectors: string[];
    excludedSelectors?: string[];
    idAttributes?: string[];
    permalinkSelectors?: string[];
  };
}

export interface DefinitionCollection {
  schemaVersion: 1;
  collectionId: string;
  name: string;
  description?: string;
  updatedAt?: string;
  definitions: SiteDefinition[];
}

export interface DefinitionSubscription {
  id: string;
  name: string;
  url: string;
  enabled: boolean;
  priority: number;
  lastChecked?: string;
  lastSuccessfulUpdate?: string;
  lastKnownGoodHash?: string;
  lastError?: string;
}

export interface NormalizedPost {
  id: string;
  text: string;
  element: Element;
  site: string;
  tabId?: number;
}

export interface PostDescriptor {
  id: string;
  text: string;
  site: string;
  tabId?: number;
  navigationId: string;
}

export interface InferenceRequest extends PostDescriptor {
  priority: QueuePriority;
  requestId: string;
}

export interface InferenceResult {
  requestId: string;
  id: string;
  textHash: string;
  label: "toxic" | "not_toxic";
  probability: number;
  navigationId: string;
  modelRevision?: string;
  /** Duration of the model invocation that produced this result, in milliseconds. */
  modelDurationMs?: number;
}

export type InferenceResponse =
  | { type: "INFERENCE_RESULT"; result: InferenceResult }
  | { error: string };

export interface Settings {
  threshold: number;
  filterMode: FilterMode;
  showScore: boolean;
  customDefinitions: SiteDefinition[];
  disabledDefinitionIds: string[];
  subscriptions: DefinitionSubscription[];
  subscriptionCollections: DefinitionCollection[];
}

export interface PageStatus {
  supported: boolean;
  paused: boolean;
  definition?: { id: string; name: string };
}

export const DEFAULT_SETTINGS: Settings = {
  threshold: 0.8,
  filterMode: "collapse",
  showScore: true,
  customDefinitions: [],
  disabledDefinitionIds: [],
  subscriptions: [],
  subscriptionCollections: []
};

export type RuntimeMessage =
  | { type: "INFER"; request: InferenceRequest }
  | { type: "INFERENCE_RESULT"; result: InferenceResult }
  | { type: "GET_SETTINGS" }
  | { type: "SET_SETTINGS"; settings: Partial<Settings> }
  | { type: "SETTINGS"; settings: Settings }
  | { type: "GET_PAGE_STATUS" }
  | { type: "PAGE_STATUS"; status: PageStatus }
  | { type: "SET_DEFINITION_PAUSED"; definitionId: string; paused: boolean }
  | { type: "REFRESH_SUBSCRIPTIONS" }
  | { type: "SUBSCRIPTIONS_UPDATED"; settings: Settings }
  | { type: "OFFSCREEN_INFER"; requests: InferenceRequest[] }
  | { type: "PING" };
