CREATE TABLE IF NOT EXISTS "Image_Table_Records" (
  record_id bigserial PRIMARY KEY,
  batch_name text NOT NULL,
  source_folder text NOT NULL,
  category_1 text,
  category_2 text,
  image_path text NOT NULL,
  image_name text NOT NULL,
  image_row_no integer NOT NULL,
  unique_key text NOT NULL,
  record_data jsonb NOT NULL,
  review_status text NOT NULL,
  review_notes text,
  manual_corrected boolean NOT NULL DEFAULT false,
  imported_at timestamptz NOT NULL DEFAULT now(),
  audit_result text,
  audit_ai_feedback text,
  audit_manual_feedback text,
  audit_checked_by text,
  audit_checked_at timestamptz,
  CONSTRAINT uq_image_table_records_unique_key UNIQUE (unique_key),
  CONSTRAINT ck_image_table_records_unique_key_present CHECK (btrim(unique_key) <> '')
);

CREATE INDEX IF NOT EXISTS idx_image_table_records_batch_name ON "Image_Table_Records"(batch_name);
CREATE INDEX IF NOT EXISTS idx_image_table_records_source_folder ON "Image_Table_Records"(source_folder);
CREATE INDEX IF NOT EXISTS idx_image_table_records_category ON "Image_Table_Records"(category_1, category_2);
CREATE INDEX IF NOT EXISTS idx_image_table_records_review_status ON "Image_Table_Records"(review_status);
CREATE INDEX IF NOT EXISTS idx_image_table_records_record_data_gin ON "Image_Table_Records" USING gin (record_data);

COMMENT ON TABLE "Image_Table_Records" IS '通用图片表格OCR归档记录表';
COMMENT ON COLUMN "Image_Table_Records".batch_name IS '处理批次名称';
COMMENT ON COLUMN "Image_Table_Records".source_folder IS '原始来源文件夹名';
COMMENT ON COLUMN "Image_Table_Records".category_1 IS '业务分类1，可按任务改名或改造成正式列';
COMMENT ON COLUMN "Image_Table_Records".category_2 IS '业务分类2，可按任务改名或改造成正式列';
COMMENT ON COLUMN "Image_Table_Records".image_path IS '原始图片路径';
COMMENT ON COLUMN "Image_Table_Records".image_name IS '原始图片文件名';
COMMENT ON COLUMN "Image_Table_Records".image_row_no IS '记录在原始图片内的行号';
COMMENT ON COLUMN "Image_Table_Records".unique_key IS '主唯一键，来自任务配置 unique_key 字段';
COMMENT ON COLUMN "Image_Table_Records".record_data IS '识别后的业务字段JSON';
COMMENT ON COLUMN "Image_Table_Records".review_status IS '自动复核或人工复核状态';
COMMENT ON COLUMN "Image_Table_Records".review_notes IS '复核提示';
COMMENT ON COLUMN "Image_Table_Records".manual_corrected IS '是否命中人工修正';
