<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';

header('Content-Type: text/plain; charset=utf-8');

function normalize_text(string $text): string
{
    $text = str_replace(["\r\n", "\r"], "\n", $text);
    $text = preg_replace('/[ \t]+/u', ' ', $text);
    $text = preg_replace("/\n{3,}/u", "\n\n", $text);

    // إصلاحات OCR الشائعة
    $text = str_replace(['املادة', 'اأملادة'], 'المادة', $text);
    $text = str_replace([')(', ' )(', ') ('], ['()', '()', '()'], $text);

    return trim($text);
}

function split_articles(string $text): array
{
    $text = normalize_text($text);

    $ordinals = [
        'الأولى'   => '1',
        'الاولى'   => '1',
        'الثانية'  => '2',
        'الثانيه'  => '2',
        'الثالثة'  => '3',
        'الثالثه'  => '3',
        'الرابعة'  => '4',
        'الرابعه'  => '4',
        'الخامسة'  => '5',
        'الخامسه'  => '5',
        'السادسة'  => '6',
        'السادسه'  => '6',
        'السابعة'  => '7',
        'السابعه'  => '7',
        'الثامنة'  => '8',
        'الثامنه'  => '8',
        'التاسعة'  => '9',
        'التاسعه'  => '9',
        'العاشرة'  => '10',
        'العاشره'  => '10',
    ];

    $pattern = '/(?:^|\n)\s*المادة\s+(?:[\(\)]?\s*(\d+)\s*[\(\)]?|([^\n]+))\s*\n(.*?)(?=(?:\n\s*المادة\s+(?:[\(\)]?\s*\d+\s*[\(\)]?|[^\n]+)\s*\n)|\z)/us';

    preg_match_all($pattern, $text, $matches, PREG_SET_ORDER);

    $articles = [];

    foreach ($matches as $m) {
        $num1 = trim((string)($m[1] ?? ''));
        $num2 = trim((string)($m[2] ?? ''));
        $body = trim((string)($m[3] ?? ''));

        if ($body === '') {
            continue;
        }

        $articleNumber = '';

        if ($num1 !== '') {
            $articleNumber = $num1;
        } else {
            $num2 = preg_replace('/[^\p{Arabic}\p{L}\p{N}\s]/u', '', $num2);
            $num2 = trim((string)$num2);

            if (isset($ordinals[$num2])) {
                $articleNumber = $ordinals[$num2];
            } elseif (preg_match('/\d+/u', $num2, $mm)) {
                $articleNumber = $mm[0];
            } else {
                continue;
            }
        }

        $lines = preg_split('/\n/u', $body, -1, PREG_SPLIT_NO_EMPTY) ?: [];
        $lines = array_map(static fn($v) => trim((string)$v), $lines);
        $lines = array_values(array_filter($lines, static fn($v) => $v !== ''));

        $articleTitle = null;
        $articleText  = $body;

        if (!empty($lines)) {
            $firstLine = $lines[0];

            if (
                mb_strlen($firstLine) <= 120 &&
                !preg_match('/^\d+[.\-]/u', $firstLine)
            ) {
                $articleTitle = $firstLine;
                array_shift($lines);
                $articleText = trim(implode("\n", $lines));
            }
        }

        if ($articleText === '') {
            $articleText = $body;
        }

        $articles[] = [
            'article_number' => $articleNumber,
            'article_title'  => $articleTitle,
            'article_text'   => $articleText,
        ];
    }

    return $articles;
}

try {
    $pdo = db();
    if (!$pdo instanceof PDO) {
        throw new RuntimeException('DB not ready');
    }

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    $txtFile = __DIR__ . '/uae_penal_law_31_2021_clean.txt';
    if (!is_file($txtFile)) {
        throw new RuntimeException('Text file not found: ' . $txtFile);
    }

    $rawText = file_get_contents($txtFile);
    if ($rawText === false || trim($rawText) === '') {
        throw new RuntimeException('Text file is empty');
    }

    // هنا فقط نجلب القانون من legal_laws
    $lawStmt = $pdo->prepare("
        SELECT id, law_title
        FROM legal_laws
        WHERE source_uid = ?
        LIMIT 1
    ");
    $lawStmt->execute(['uae-penal-31-2021']);
    $law = $lawStmt->fetch();

    if (!$law) {
        throw new RuntimeException('Law not found in legal_laws: uae-penal-31-2021');
    }

    $lawId = (int)$law['id'];

    $articles = split_articles($rawText);

    if (!$articles) {
        echo "لم يتم التعرف على المواد تلقائياً.\n\n";
        echo "أول 2000 حرف من الملف:\n\n";
        echo mb_substr(normalize_text($rawText), 0, 2000);
        exit;
    }

    $pdo->beginTransaction();

    $insert = $pdo->prepare("
        INSERT INTO legal_articles
        (law_id, article_number, article_title, article_text, keywords)
        VALUES (?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
            article_title = VALUES(article_title),
            article_text  = VALUES(article_text),
            keywords      = VALUES(keywords)
    ");

    $count = 0;

    foreach ($articles as $a) {
        $articleNumber = trim((string)$a['article_number']);
        $articleTitle  = $a['article_title'] !== null ? trim((string)$a['article_title']) : null;
        $articleText   = trim((string)$a['article_text']);

        if ($articleNumber === '' || $articleText === '') {
            continue;
        }

        $keywords = implode(',', array_filter([
            'قانون الجرائم والعقوبات',
            'مرسوم بقانون اتحادي رقم 31 لسنة 2021',
            'المادة ' . $articleNumber,
            $articleTitle ?: null
        ]));

        $insert->execute([
            $lawId,
            $articleNumber,
            $articleTitle,
            $articleText,
            $keywords
        ]);

        $count++;
    }

    $pdo->commit();

    echo "تم إدخال/تحديث المواد بنجاح\n";
    echo "law_id = {$lawId}\n";
    echo "articles = {$count}\n";

} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    http_response_code(500);
    echo "ERROR: " . $e->getMessage();
}