<?php
declare(strict_types=1);

class Honeypot
{
    private string $blockFile;
    private int $blockDuration = 86400; // 24h

    public function __construct(string $dataDir)
    {
        $this->blockFile = $dataDir . '/blocked_ips.json';
    }

    public function isBlocked(string $ip): bool
    {
        $now = time();
        foreach ($this->loadList() as $entry) {
            if ($entry['ip'] === $ip && strtotime($entry['blocked_until']) > $now) {
                return true;
            }
        }
        return false;
    }

    public function block(string $ip, string $reason = 'honeypot'): void
    {
        $list  = array_values(array_filter($this->loadList(), fn($e) => $e['ip'] !== $ip));
        $list[] = [
            'ip'            => $ip,
            'blocked_until' => date('c', time() + $this->blockDuration),
            'reason'        => $reason,
        ];
        $this->saveList($list);
    }

    public function handleHoneypotRequest(): never
    {
        $this->block($this->getClientIp(), 'honeypot');
        $this->deny();
    }

    public function enforceBlock(): void
    {
        if ($this->isBlocked($this->getClientIp())) {
            $this->deny();
        }
    }

    public function getClientIp(): string
    {
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }

    private function deny(): never
    {
        http_response_code(403);
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'error' => 'Forbidden', 'code' => 403]);
        exit;
    }

    private function loadList(): array
    {
        if (!file_exists($this->blockFile)) return [];
        return json_decode(file_get_contents($this->blockFile), true) ?? [];
    }

    private function saveList(array $list): void
    {
        $tmp = $this->blockFile . '.tmp';
        file_put_contents($tmp, json_encode($list, JSON_PRETTY_PRINT), LOCK_EX);
        rename($tmp, $this->blockFile);
    }
}