<?php
/**
 * ICYLAB Runtime Target Diagnostic v6.9
 * CLI only. Read-only. Does not print credentials or tokens.
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit("CLI only\n");
}

$options = getopt('', array('app-root::'));
$appRoot = isset($options['app-root']) && $options['app-root'] !== false
    ? (string) $options['app-root']
    : dirname(__DIR__);
$appRoot = realpath($appRoot) ?: rtrim($appRoot, DIRECTORY_SEPARATOR);

$configPath = $appRoot . '/core/config.php';
$dbPath = $appRoot . '/core/database.php';

if (!is_file($configPath) || !is_file($dbPath)) {
    fwrite(STDERR, "FAIL: core/config.php or core/database.php not found under app root.\n");
    exit(1);
}

require_once $configPath;
require_once $dbPath;

function diag_bool($value)
{
    return $value ? 'true' : 'false';
}

function diag_scalar(PDO $pdo, $sql)
{
    $stmt = $pdo->query($sql);
    return $stmt ? $stmt->fetchColumn() : null;
}

function diag_file(PDO $pdo, $appRoot, $relativePath)
{
    $path = $appRoot . '/' . $relativePath;
    echo "FILE {$relativePath}\n";
    echo "  exists: " . (is_file($path) ? 'yes' : 'no') . "\n";
    if (is_file($path)) {
        echo "  sha256: " . hash_file('sha256', $path) . "\n";
        echo "  modified_at: " . date('c', filemtime($path)) . "\n";
    }
}

try {
    $pdo = db();
    $runtimeDb = (string) diag_scalar($pdo, 'SELECT DATABASE()');
    $serverNow = (string) diag_scalar($pdo, 'SELECT NOW()');

    $privatePath = getenv('ICYLAB_PRIVATE_CONFIG_PATH');
    if ($privatePath === false || trim((string) $privatePath) === '') {
        $privatePath = $appRoot . '/core/private_config.php';
    }
    $privateRealPath = realpath((string) $privatePath) ?: (string) $privatePath;

    echo "========================================================================\n";
    echo "ICYLAB Runtime Target Diagnostic v6.9\n";
    echo "READ ONLY - no credentials or tokens are printed\n";
    echo "========================================================================\n";
    echo "php_version: " . PHP_VERSION . "\n";
    echo "executed_at: " . date('c') . "\n";
    echo "server_db_time: " . $serverNow . "\n";
    echo "app_root: " . $appRoot . "\n";
    echo "config_path: " . (realpath($configPath) ?: $configPath) . "\n";
    echo "private_config_path: " . $privateRealPath . "\n";
    echo "private_config_exists: " . (is_file($privateRealPath) ? 'yes' : 'no') . "\n";
    echo "app_env: " . (defined('APP_ENV') ? APP_ENV : 'undefined') . "\n";
    echo "app_url: " . (defined('APP_URL') ? APP_URL : 'undefined') . "\n";
    echo "db_name_constant: " . (defined('DB_NAME') ? DB_NAME : 'undefined') . "\n";
    echo "db_name_runtime: " . $runtimeDb . "\n";
    echo "facto_default_environment: " . (defined('FACTO_DEFAULT_ENVIRONMENT') ? FACTO_DEFAULT_ENVIRONMENT : 'undefined') . "\n";
    echo "billing_production_read_enabled: " . diag_bool(defined('BILLING_PRODUCTION_READ_ENABLED') && BILLING_PRODUCTION_READ_ENABLED) . "\n";
    echo "billing_production_finance_enabled: " . diag_bool(defined('BILLING_PRODUCTION_FINANCE_ENABLED') && BILLING_PRODUCTION_FINANCE_ENABLED) . "\n";
    echo "billing_production_issue_enabled: " . diag_bool(defined('BILLING_PRODUCTION_ISSUE_ENABLED') && BILLING_PRODUCTION_ISSUE_ENABLED) . "\n";

    echo "------------------------------------------------------------------------\n";
    echo "DATABASE INVENTORY\n";
    echo "facto_documents_production: " . (int) diag_scalar($pdo, "SELECT COUNT(*) FROM facto_documents WHERE BINARY environment=BINARY 'production'") . "\n";
    echo "facto_documents_sandbox: " . (int) diag_scalar($pdo, "SELECT COUNT(*) FROM facto_documents WHERE BINARY environment=BINARY 'sandbox'") . "\n";
    echo "facto_inbox_production: " . (int) diag_scalar($pdo, "SELECT COUNT(*) FROM facto_inbox_documents WHERE BINARY environment=BINARY 'production'") . "\n";
    echo "facto_inbox_sandbox: " . (int) diag_scalar($pdo, "SELECT COUNT(*) FROM facto_inbox_documents WHERE BINARY environment=BINARY 'sandbox'") . "\n";
    echo "document_858_production: " . (int) diag_scalar($pdo, "SELECT COUNT(*) FROM facto_documents WHERE BINARY environment=BINARY 'production' AND document_id='858'") . "\n";
    echo "inbox_516_production: " . (int) diag_scalar($pdo, "SELECT COUNT(*) FROM facto_inbox_documents WHERE BINARY environment=BINARY 'production' AND inbox_document_id='516'") . "\n";
    echo "latest_sync_log_id: " . (int) diag_scalar($pdo, "SELECT COALESCE(MAX(id),0) FROM facto_sync_logs") . "\n";
    echo "latest_sync_log_at: " . (string) diag_scalar($pdo, "SELECT COALESCE(MAX(synced_at),'') FROM facto_sync_logs") . "\n";

    echo "------------------------------------------------------------------------\n";
    echo "DEPLOYED FILE FINGERPRINTS\n";
    diag_file($pdo, $appRoot, 'cron/sync_facto_documents.php');
    diag_file($pdo, $appRoot, 'cron/sync_facto_inbox_documents.php');
    diag_file($pdo, $appRoot, 'services/facto/FactoDocumentsSyncService.php');
    diag_file($pdo, $appRoot, 'services/facto/FactoInboxDocumentsSyncService.php');
    diag_file($pdo, $appRoot, 'core/config.php');

    echo "------------------------------------------------------------------------\n";
    if ($runtimeDb !== 'icylab_app') {
        echo "DECISION: BLOCKED - runtime is connected to {$runtimeDb}, not icylab_app.\n";
        exit(2);
    }

    echo "DECISION: DATABASE TARGET IS icylab_app. Investigate stale output or different app root if sync data is still absent.\n";
    exit(0);
} catch (Throwable $e) {
    fwrite(STDERR, "FAIL: " . $e->getMessage() . "\n");
    exit(1);
}