-- database/ai_schema.sql

CREATE TABLE `ai_providers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `provider_class` varchar(100) NOT NULL, -- e.g., 'GeminiProvider'
  `api_key` varchar(255) DEFAULT NULL,
  `active_model` varchar(100) DEFAULT NULL,
  `priority` int(11) NOT NULL DEFAULT 10,
  `is_active` tinyint(1) NOT NULL DEFAULT 1,
  `is_cooldown` tinyint(1) NOT NULL DEFAULT 0,
  `cooldown_until` timestamp NULL DEFAULT NULL,
  `total_requests` int(11) NOT NULL DEFAULT 0,
  `failed_requests` int(11) NOT NULL DEFAULT 0,
  `last_error` text DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `ai_requests` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `provider_id` int(11) DEFAULT NULL,
  `model_used` varchar(100) NOT NULL,
  `prompt_tokens` int(11) DEFAULT 0,
  `completion_tokens` int(11) DEFAULT 0,
  `response_time_ms` int(11) NOT NULL,
  `status` enum('success','error') NOT NULL DEFAULT 'success',
  `error_message` text DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`provider_id`) REFERENCES `ai_providers`(`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `ai_failover_logs` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `failed_provider_id` int(11) NOT NULL,
  `fallback_provider_id` int(11) NOT NULL,
  `reason` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Seed Data (Example)
INSERT INTO `ai_providers` (`name`, `provider_class`, `active_model`, `priority`) VALUES
('Gemini', 'GeminiProvider', 'gemini-pro', 1),
('Groq', 'GroqProvider', 'llama3-70b-8192', 2),
('Together AI', 'TogetherProvider', 'meta-llama/Llama-3-70b-chat-hf', 3),
('DeepSeek', 'DeepSeekProvider', 'deepseek-coder', 4),
('Ollama Local', 'OllamaProvider', 'llama3', 99); -- 99 implies last resort fallback
