CREATE TABLE IF NOT EXISTS llm_trace_runs (
  job_id TEXT PRIMARY KEY,
  case_id TEXT,
  status TEXT NOT NULL,
  current_stage TEXT NOT NULL,
  trace_completeness TEXT NOT NULL,
  error_stage TEXT,
  error_summary TEXT,
  started_at TEXT NOT NULL,
  finished_at TEXT,
  updated_at TEXT NOT NULL,
  FOREIGN KEY (job_id) REFERENCES article_jobs(id) ON DELETE CASCADE,
  FOREIGN KEY (case_id) REFERENCES optimization_cases(id) ON DELETE SET NULL
);

CREATE TABLE IF NOT EXISTS llm_trace_calls (
  call_id TEXT PRIMARY KEY,
  job_id TEXT NOT NULL,
  sequence INTEGER NOT NULL,
  task TEXT NOT NULL,
  workflow_stage TEXT NOT NULL,
  rewrite_round INTEGER,
  provider TEXT NOT NULL,
  model TEXT NOT NULL,
  status TEXT NOT NULL,
  request_object_key TEXT,
  response_object_key TEXT,
  token_usage TEXT,
  schema_name TEXT,
  schema_valid INTEGER,
  validation_issues TEXT NOT NULL DEFAULT '[]',
  business_status TEXT,
  duration_ms INTEGER,
  started_at TEXT NOT NULL,
  responded_at TEXT,
  validated_at TEXT,
  failed_at TEXT,
  error_type TEXT,
  error_summary TEXT,
  UNIQUE (job_id, sequence),
  FOREIGN KEY (job_id) REFERENCES llm_trace_runs(job_id) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_llm_trace_runs_status_updated
  ON llm_trace_runs(status, updated_at DESC);

CREATE INDEX IF NOT EXISTS idx_llm_trace_calls_job_sequence
  ON llm_trace_calls(job_id, sequence);
