<?php

function ht_comment_key(array $item): string {
    return md5(strtolower(trim((string)($item['ip'] ?? ''))) . '|' . trim((string)($item['date'] ?? '')) . '|' . trim((string)($item['message'] ?? '')));
}

function ht_comment_split_chunks(string $raw): array {
    $raw = str_replace(["\r\n", "\r"], "\n", $raw);
    // Repair old malformed separators like "Approved: true---IP: ..."
    $raw = preg_replace('/(Approved\s*:\s*(?:true|false|1|0|yes|no))\s*---\s*(?=IP\s*:)/i', "$1\n---\n", $raw);
    $raw = preg_replace('/(Reply\s*:.*)\s*---\s*(?=IP\s*:)/i', "$1\n---\n", $raw);
    $parts = preg_split('/\n\s*---\s*\n|---\s*(?=IP\s*:)|\A\s*---\s*\n?/i', trim($raw));
    $parts = array_values(array_filter(array_map('trim', $parts), fn($p) => $p !== ''));
    return $parts;
}

function ht_comment_parse_chunk(string $chunk): array {
    $lines = preg_split('/\n/', trim($chunk));
    $item = [
        'ip' => '',
        'date' => '',
        'message' => '',
        'approved' => false,
        'inline_reply' => '',
        '_raw' => trim($chunk),
    ];

    $messageLines = [];
    $captureMessage = false;
    foreach ($lines as $line) {
        $line = rtrim($line, "\r\n");
        if (trim($line) === '---') {
            continue;
        }
        if (preg_match('/^IP\s*:\s*(.*)$/i', $line, $m)) {
            $item['ip'] = trim($m[1]);
            $captureMessage = false;
            continue;
        }
        if (preg_match('/^Date\s*:\s*(.*)$/i', $line, $m)) {
            $item['date'] = trim($m[1]);
            $captureMessage = false;
            continue;
        }
        if (preg_match('/^Approved\s*:\s*(.*)$/i', $line, $m)) {
            $v = strtolower(trim($m[1]));
            $item['approved'] = in_array($v, ['1','true','yes','y'], true);
            $captureMessage = false;
            continue;
        }
        if (preg_match('/^Reply\s*:\s*(.*)$/i', $line, $m)) {
            $item['inline_reply'] = preg_replace('/\s*---\s*$/', '', trim($m[1]));
            $captureMessage = false;
            continue;
        }
        if (preg_match('/^Message\s*:\s*(.*)$/i', $line, $m)) {
            $captureMessage = true;
            $first = trim($m[1]);
            if ($first !== '') $messageLines[] = $first;
            continue;
        }

        // If the line is another simple key, ignore it.
        if (preg_match('/^[A-Za-z][A-Za-z0-9 _-]*\s*:/', $line)) {
            $captureMessage = false;
            continue;
        }

        // Old format stored comment body as bare lines between Date and Approved.
        $messageLines[] = $line;
    }

    $item['message'] = preg_replace('/\n{3,}/', "\n\n", trim(implode("\n", $messageLines)));
    $item['inline_reply'] = preg_replace('/\s*---\s*$/', '', trim((string)$item['inline_reply']));
    return $item;
}

function ht_read_comments(string $commentsFile, string $repliesFile): array {
    $replies = [];
    if (is_file($repliesFile)) {
        $json = json_decode((string)file_get_contents($repliesFile), true);
        if (is_array($json)) $replies = $json;
    }

    $items = [];
    if (is_file($commentsFile)) {
        $raw = (string)file_get_contents($commentsFile);
        foreach (ht_comment_split_chunks($raw) as $chunk) {
            $item = ht_comment_parse_chunk($chunk);
            if ($item['message'] === '' && $item['ip'] === '' && $item['date'] === '') continue;
            $item['key'] = ht_comment_key($item);
            if (!isset($replies[$item['key']]) && $item['inline_reply'] !== '') {
                $replies[$item['key']] = [
                    'text' => $item['inline_reply'],
                    'by' => 'legacy',
                    'ts' => time(),
                ];
            }
            if (isset($replies[$item['key']]['text'])) {
                $replies[$item['key']]['text'] = preg_replace('/\s*---\s*$/', '', trim((string)$replies[$item['key']]['text']));
            }
            $item['reply'] = (string)($replies[$item['key']]['text'] ?? '');
            if ($item['message'] === '' && $item['ip'] === '' && $item['date'] === '' && $item['reply'] === '') continue;
            $items[] = $item;
        }
    }

    return ['items_newest' => array_reverse($items), 'replies' => $replies, 'items_oldest' => $items];
}

function ht_write_comments(string $commentsFile, array $itemsOldest): bool {
    $out = '';
    foreach ($itemsOldest as $item) {
        $ip = trim((string)($item['ip'] ?? 'unknown'));
        $date = trim((string)($item['date'] ?? date('Y-m-d H:i:s')));
        $message = trim((string)($item['message'] ?? ''));
        $approved = !empty($item['approved']) ? '1' : '0';
        $block = "IP: {$ip}\nDate: {$date}\nMessage:";
        if ($message !== '') {
            $block .= "\n" . $message;
        }
        $block .= "\nApproved: {$approved}";
        $out .= $block . "\n---\n";
    }
    if (file_exists($commentsFile)) @copy($commentsFile, $commentsFile . '.bak');
    return file_put_contents($commentsFile, $out, LOCK_EX) !== false;
}
