-- Migration 002: Agent System
-- Creates tables for agent registry and instance management

-- Agents table (registry of agent types/roles)
DEFINE TABLE agents SCHEMAFULL
    PERMISSIONS
        FOR select FULL
        FOR create, update, delete WHERE "admin" IN $auth.roles OR "devops" IN $auth.roles;

DEFINE FIELD id ON TABLE agents TYPE record<agents>;
DEFINE FIELD role ON TABLE agents TYPE string ASSERT $value INSIDE [
    "architect", "developer", "code_reviewer", "tester",
    "documenter", "marketer", "presenter", "devops",
    "monitor", "security", "project_manager", "decision_maker"
];
DEFINE FIELD name ON TABLE agents TYPE string ASSERT $value != NONE;
DEFINE FIELD version ON TABLE agents TYPE string DEFAULT "0.1.0";
DEFINE FIELD status ON TABLE agents TYPE string ASSERT $value INSIDE ["active", "inactive", "updating", "error"] DEFAULT "active";
DEFINE FIELD capabilities ON TABLE agents TYPE array<string> DEFAULT [];
DEFINE FIELD skills ON TABLE agents TYPE array<string> DEFAULT [];
DEFINE FIELD llm_provider ON TABLE agents TYPE string ASSERT $value INSIDE ["claude", "openai", "gemini", "ollama"];
DEFINE FIELD llm_model ON TABLE agents TYPE string ASSERT $value != NONE;
DEFINE FIELD max_concurrent_tasks ON TABLE agents TYPE int DEFAULT 3 ASSERT $value > 0;
DEFINE FIELD created_at ON TABLE agents TYPE datetime DEFAULT time::now();

DEFINE INDEX idx_agents_role ON TABLE agents COLUMNS role UNIQUE;
DEFINE INDEX idx_agents_status ON TABLE agents COLUMNS status;
DEFINE INDEX idx_agents_provider ON TABLE agents COLUMNS llm_provider;

-- Agent instances table (runtime instances of agents)
DEFINE TABLE agent_instances SCHEMAFULL
    PERMISSIONS
        FOR select FULL
        FOR create, update, delete WHERE "admin" IN $auth.roles OR "devops" IN $auth.roles;

DEFINE FIELD id ON TABLE agent_instances TYPE record<agent_instances>;
DEFINE FIELD agent_id ON TABLE agent_instances TYPE string ASSERT $value != NONE;
DEFINE FIELD pod_id ON TABLE agent_instances TYPE string ASSERT $value != NONE;
DEFINE FIELD ip ON TABLE agent_instances TYPE string;
DEFINE FIELD port ON TABLE agent_instances TYPE int ASSERT $value > 0 AND $value < 65536;
DEFINE FIELD start_time ON TABLE agent_instances TYPE datetime DEFAULT time::now();
DEFINE FIELD last_heartbeat ON TABLE agent_instances TYPE datetime DEFAULT time::now();
DEFINE FIELD tasks_completed ON TABLE agent_instances TYPE int DEFAULT 0;
DEFINE FIELD uptime_percentage ON TABLE agent_instances TYPE float DEFAULT 100.0;
DEFINE FIELD status ON TABLE agent_instances TYPE string ASSERT $value INSIDE ["running", "stopped", "error"] DEFAULT "running";

DEFINE INDEX idx_agent_instances_agent ON TABLE agent_instances COLUMNS agent_id;
DEFINE INDEX idx_agent_instances_pod ON TABLE agent_instances COLUMNS pod_id;
DEFINE INDEX idx_agent_instances_status ON TABLE agent_instances COLUMNS status;
DEFINE INDEX idx_agent_instances_heartbeat ON TABLE agent_instances COLUMNS last_heartbeat;
