<?php

declare(strict_types=1);

namespace KimaAI\Models;

defined('ABSPATH') || exit;

class EmbeddingLogsModel {
  use HasSchema;

  public const TABLE = 'kimaai_embedding_logs';
  public const PRIMARY_KEY = 'id';

  public const COLUMNS = [
    'id' => 'BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT',
    'batch_id' => 'VARCHAR(64) NOT NULL',
    'post_id' => 'BIGINT(20) UNSIGNED NULL',
    'vector_id' => 'VARCHAR(191) NULL',
    'stage' => 'VARCHAR(32) NOT NULL', // Stages: start, clean, chunk, vectorizing, vectorized, upserting, upserted, error, done
    'level' => "VARCHAR(10) NOT NULL DEFAULT 'info'", // info|error
    'message' => 'TEXT NULL',
    'created_at' => 'DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
  ];

  /**
   * Indexes ONLY.
   */
  public const INDEXES = [
    'KEY batch_id (batch_id)',
    'KEY post_id (post_id)',
    'KEY created (created_at)',
  ];

  /**
   * Returns the fully-qualified table name.
   *
   * @return string
   */
  private static function table(): string {
    global $wpdb;
    return $wpdb->prefix . self::TABLE;
  }

  /**
   * Inserts a log row and returns the new ID.
   *
   * @param array $row Log data.
   * @return int The inserted row ID.
   */
  public static function add(array $row): int {
    global $wpdb;

    $row = array_merge([
      'batch_id' => '',
      'post_id' => null,
      'vector_id' => null,
      'stage' => 'info',
      'level' => 'info',
      'message' => null,
      'created_at' => current_time('mysql'),
    ], $row);

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
    $wpdb->insert(self::table(), $row, ['%s', '%d', '%s', '%s', '%s', '%s', '%s']);

    return (int) $wpdb->insert_id;
  }

  /**
   * Tail logs by batch or post (after_id for incremental polling)
   */
  public static function tail(array $args): array {
    global $wpdb;

    $where = [];
    $vals = [];

    if (!empty($args['batch_id'])) {
      $where[] = 'batch_id=%s';
      $vals[] = $args['batch_id'];
    }

    if (!empty($args['post_id'])) {
      $where[] = 'post_id=%d';
      $vals[] = (int) $args['post_id'];
    }

    if (!empty($args['after_id'])) {
      $where[] = 'id>%d';
      $vals[] = (int) $args['after_id'];
    }

    $limit = max(1, min(500, (int) ($args['limit'] ?? 100)));
    $where_clause = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
    $sql = 'SELECT * FROM ' . self::table() . " {$where_clause} ORDER BY id ASC LIMIT {$limit}";

    // phpcs:ignore WordPress.DB
    return $wpdb->get_results($wpdb->prepare($sql, ...$vals), ARRAY_A) ?: [];
  }
}
