-- AgentCoord 数据库表结构
-- 基于 DATABASE_DESIGN.md 设计
-- 执行方式: psql -U postgres -d agentcoord -f schema.sql

-- =============================================================================
-- 表1: multi_agent_tasks (多智能体任务记录)
-- 状态枚举: pending/planning/generating/executing/completed/failed
-- =============================================================================
CREATE TABLE IF NOT EXISTS multi_agent_tasks (
    task_id VARCHAR(64) PRIMARY KEY,
    user_id VARCHAR(64) NOT NULL,
    query TEXT NOT NULL,
    agents_info JSONB NOT NULL,
    task_outline JSONB,
    assigned_agents JSONB,
    agent_scores JSONB,
    result JSONB,
    status VARCHAR(20) DEFAULT 'pending',
    execution_count INTEGER DEFAULT 0,
    generation_id VARCHAR(64),
    execution_id VARCHAR(64),
    rehearsal_log JSONB,
    branches JSONB,                    -- 任务大纲探索分支数据
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_multi_agent_tasks_user_id ON multi_agent_tasks(user_id);
CREATE INDEX IF NOT EXISTS idx_multi_agent_tasks_created_at ON multi_agent_tasks(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_multi_agent_tasks_status ON multi_agent_tasks(status);
CREATE INDEX IF NOT EXISTS idx_multi_agent_tasks_generation_id ON multi_agent_tasks(generation_id);
CREATE INDEX IF NOT EXISTS idx_multi_agent_tasks_execution_id ON multi_agent_tasks(execution_id);

-- =============================================================================
-- 表2: user_agents (用户保存的智能体配置) - 可选表
-- =============================================================================
CREATE TABLE IF NOT EXISTS user_agents (
    id VARCHAR(64) PRIMARY KEY,
    user_id VARCHAR(64) NOT NULL,
    agent_name VARCHAR(100) NOT NULL,
    agent_config JSONB NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_user_agents_user_id ON user_agents(user_id);

-- =============================================================================
-- 更新时间触发器函数
-- =============================================================================
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ language 'plpgsql';

-- 为 multi_agent_tasks 表创建触发器
CREATE TRIGGER update_multi_agent_tasks_updated_at
    BEFORE UPDATE ON multi_agent_tasks
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();

DO $$
BEGIN
    RAISE NOTICE '✅ PostgreSQL 数据库表结构创建完成！';
    RAISE NOTICE '表: multi_agent_tasks (多智能体任务记录)';
    RAISE NOTICE '表: user_agents (用户智能体配置)';
END $$;
