-- Agent event log, realization evidence, and sync state tables

-- agent_events: log of agent actions (PR comments, doc PRs, staleness reports)
CREATE TABLE IF NOT EXISTS agent_events (
    id BIGSERIAL PRIMARY KEY,
    repo TEXT NOT NULL,
    event_type TEXT NOT NULL,
    pr_number INT,
    issue_number INT,
    actor TEXT NOT NULL DEFAULT '',
    detail JSONB NOT NULL DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_agent_events_repo ON agent_events (repo);
CREATE INDEX IF NOT EXISTS idx_agent_events_event_type ON agent_events (event_type);
CREATE INDEX IF NOT EXISTS idx_agent_events_created_at ON agent_events (created_at);
CREATE INDEX IF NOT EXISTS idx_agent_events_pr_number ON agent_events (pr_number)
    WHERE pr_number IS NOT NULL;

-- realization_evidence: which PRs/code realize which spec acceptance criteria
CREATE TABLE IF NOT EXISTS realization_evidence (
    id BIGSERIAL PRIMARY KEY,
    repo TEXT NOT NULL,
    spec_path TEXT NOT NULL,
    section_id TEXT NOT NULL,
    ac_text TEXT NOT NULL DEFAULT '',
    status TEXT NOT NULL DEFAULT 'not_addressed',
    pr_number INT NOT NULL,
    pr_url TEXT NOT NULL DEFAULT '',
    evidence_files JSONB NOT NULL DEFAULT '[]',
    assessed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (repo, spec_path, section_id, ac_text, pr_number)
);

CREATE INDEX IF NOT EXISTS idx_realization_evidence_repo ON realization_evidence (repo);
CREATE INDEX IF NOT EXISTS idx_realization_evidence_spec ON realization_evidence (repo, spec_path);

-- sync_state: last sync timestamp per spec/ticket pair
CREATE TABLE IF NOT EXISTS sync_state (
    id BIGSERIAL PRIMARY KEY,
    repo TEXT NOT NULL,
    spec_path TEXT NOT NULL,
    section_id TEXT NOT NULL,
    ticket_id TEXT NOT NULL,
    last_synced_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_status TEXT NOT NULL DEFAULT '',
    UNIQUE (repo, spec_path, section_id, ticket_id)
);

CREATE INDEX IF NOT EXISTS idx_sync_state_repo ON sync_state (repo);
