INSERT INTO agents (id, name, role, tool, custom_prompt, is_default, created_at, updated_at)
SELECT
    'default-reviewer-agent',
    'Default Reviewer',
    'reviewer',
    'codex',
    '',
    1,
    strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),
    strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
WHERE NOT EXISTS (
    SELECT 1 FROM agents WHERE role = 'reviewer' AND is_default = 1
);

ALTER TABLE watched_trackers ADD COLUMN reviewer_agent_id TEXT REFERENCES agents(id);

UPDATE watched_trackers
SET reviewer_agent_id = 'default-reviewer-agent'
WHERE reviewer_agent_id IS NULL OR TRIM(reviewer_agent_id) = '';

UPDATE watched_trackers
SET status = CASE
    WHEN analyst_agent_id IS NULL OR developer_agent_id IS NULL OR reviewer_agent_id IS NULL THEN 'invalid'
    ELSE 'valid'
END;

ALTER TABLE graylog_credentials ADD COLUMN reviewer_agent_id TEXT REFERENCES agents(id);

UPDATE graylog_credentials
SET reviewer_agent_id = 'default-reviewer-agent'
WHERE reviewer_agent_id IS NULL OR TRIM(reviewer_agent_id) = '';

ALTER TABLE processed_tickets ADD COLUMN review_report TEXT;
