#!/usr/bin/env php
<?php
/**
 * MCP Memory Server - Observation Migration Script
 *
 * Migrates observations from Entity.observations LIST property
 * to first-class Observation vertices with HAS_OBSERVATION edges.
 *
 * Usage: php bin/migrate-observations [--dry-run]
 * Exit: 0 = success, 1 = error
 *
 * Run this ONCE on existing databases before deploying v1.2.0.
 */

require_once __DIR__ . '/../includes/bootstrap.inc.php';

$dryRun = in_array('--dry-run', $argv);

if ($dryRun) {
    echo "DRY RUN - no changes will be made\n\n";
}

// Load settings
$config = new IniConfig(APPLICATION_CONFDIR . '/settings.ini');
$db = new ArcadeDB(
    $config->get('arcadedb', 'host', 'localhost'),
    (int) $config->get('arcadedb', 'port', 2480),
    $config->get('arcadedb', 'user', 'root'),
    $config->get('arcadedb', 'pass', '')
);
$database = $config->get('arcadedb', 'database', 'memory');

echo "MCP Memory Server - Observation Migration\n";
echo "Database: {$database}\n\n";

// Ensure new schema exists
echo "Creating Observation vertex type and HAS_OBSERVATION edge type...\n";
if (!$dryRun) {
    $db->command($database, "CREATE VERTEX TYPE Observation IF NOT EXISTS");
    $db->command($database, "CREATE PROPERTY Observation.content IF NOT EXISTS STRING");
    $db->command($database, "CREATE PROPERTY Observation.createdAt IF NOT EXISTS DATETIME");
    $db->command($database, "CREATE PROPERTY Observation.source IF NOT EXISTS STRING");
    $db->command($database, "CREATE PROPERTY Observation.importance IF NOT EXISTS DOUBLE");
    $db->command($database, "CREATE INDEX IF NOT EXISTS ON Observation(content) NOTUNIQUE");
    $db->command($database, "CREATE EDGE TYPE HAS_OBSERVATION IF NOT EXISTS");
}

// Find entities with observations LIST property
$result = $db->query($database, "SELECT name, observations FROM Entity WHERE observations IS NOT NULL AND observations.size() > 0");
$entities = $result['result'] ?? [];

if (empty($entities)) {
    echo "No entities with observations LIST found. Nothing to migrate.\n";
    exit(0);
}

echo "Found " . count($entities) . " entities with observations to migrate.\n\n";

$totalObs = 0;
$errors = 0;

foreach ($entities as $entity) {
    $name = $entity['name'] ?? '';
    $observations = $entity['observations'] ?? [];

    if (empty($name) || empty($observations)) {
        continue;
    }

    echo "  {$name}: " . count($observations) . " observations\n";

    foreach ($observations as $obs) {
        if (!is_string($obs) || empty(trim($obs))) {
            continue;
        }

        if ($dryRun) {
            echo "    [dry-run] Would create Observation: {$obs}\n";
            $totalObs++;
            continue;
        }

        try {
            // Create Observation vertex
            $insertResult = $db->command($database,
                "INSERT INTO Observation SET content = :content, createdAt = sysdate(), source = 'migration'",
                ['content' => $obs]
            );

            $obsRid = $insertResult['result'][0]['@rid'] ?? null;
            if ($obsRid && preg_match('/^#\d+:\d+$/', $obsRid)) {
                // Create HAS_OBSERVATION edge
                $db->command($database,
                    "CREATE EDGE HAS_OBSERVATION FROM (SELECT FROM Entity WHERE name = :name) TO {$obsRid}",
                    ['name' => $name]
                );
                $totalObs++;
            } else {
                echo "    WARNING: Could not get RID for observation: {$obs}\n";
                $errors++;
            }
        } catch (\Exception $e) {
            echo "    ERROR: {$e->getMessage()}\n";
            $errors++;
        }
    }

    // Remove the LIST property from the entity
    if (!$dryRun) {
        try {
            $db->command($database,
                "UPDATE Entity SET observations = NULL WHERE name = :name",
                ['name' => $name]
            );
        } catch (\Exception $e) {
            echo "    WARNING: Could not clear observations LIST: {$e->getMessage()}\n";
        }
    }
}

echo "\n";
echo "Migrated: {$totalObs} observations\n";
echo "Errors:   {$errors}\n";

if ($errors > 0) {
    echo "\nWARNING: Some observations failed to migrate. Review errors above.\n";
    exit(1);
}

echo "\nMigration complete.\n";
exit(0);
