-- Migration 015: Blog Feedback System for FO_Blog_LLM training

CREATE TABLE IF NOT EXISTS blog_feedback (
  id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  blog_id         UUID REFERENCES blog_drafts(id) ON DELETE CASCADE,

  -- Ratings (1-10)
  score_overall           INTEGER CHECK (score_overall BETWEEN 1 AND 10),
  score_technical_depth   INTEGER CHECK (score_technical_depth BETWEEN 1 AND 10),
  score_real_world        INTEGER CHECK (score_real_world BETWEEN 1 AND 10),
  score_clarity           INTEGER CHECK (score_clarity BETWEEN 1 AND 10),
  score_originality       INTEGER CHECK (score_originality BETWEEN 1 AND 10),
  score_engineer_voice    INTEGER CHECK (score_engineer_voice BETWEEN 1 AND 10),
  score_decision_value    INTEGER CHECK (score_decision_value BETWEEN 1 AND 10),
  score_failure_scenarios INTEGER CHECK (score_failure_scenarios BETWEEN 1 AND 10),
  score_opinion_strength  INTEGER CHECK (score_opinion_strength BETWEEN 1 AND 10),

  -- Free text feedback (this gets fed back to the LLM)
  feedback_text   TEXT,
  reviewer        TEXT DEFAULT 'human',        -- human, auto_qa, llm_self

  -- Context for LLM training
  blog_type       TEXT,                        -- market_alert, migration_guide, etc.
  blog_topic      TEXT,                        -- original topic
  improvements    JSONB,                       -- array of specific improvement suggestions

  -- Was this feedback used for training?
  fed_to_llm      BOOLEAN DEFAULT FALSE,
  fed_at          TIMESTAMPTZ,

  created_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_blog_feedback_blog ON blog_feedback(blog_id);
CREATE INDEX IF NOT EXISTS idx_blog_feedback_score ON blog_feedback(score_overall);
CREATE INDEX IF NOT EXISTS idx_blog_feedback_unfed ON blog_feedback(fed_to_llm) WHERE fed_to_llm = FALSE;

-- Track which LLM model/config was used for each blog
ALTER TABLE blog_drafts ADD COLUMN IF NOT EXISTS llm_model TEXT DEFAULT 'qwen2.5:14b';
ALTER TABLE blog_drafts ADD COLUMN IF NOT EXISTS llm_temperature NUMERIC DEFAULT 0.7;
ALTER TABLE blog_drafts ADD COLUMN IF NOT EXISTS pipeline_version TEXT DEFAULT 'v3-flexoptix-style';
ALTER TABLE blog_drafts ADD COLUMN IF NOT EXISTS pipeline_steps_completed INTEGER DEFAULT 0;
ALTER TABLE blog_drafts ADD COLUMN IF NOT EXISTS auto_qa_score JSONB;
