<?php

namespace App\Support;

use App\Services\PaperIdGenerator;
use InvalidArgumentException;

class PaperNaming
{
    public static function assembleTypeLabel(int $assembleType): string
    {
        return match ($assembleType) {
            0, 9 => '智能摸底',
            1, 4, 8 => '智能组题',
            2 => '知识点组题',
            3 => '教材组题',
            5 => '智能追练',
            15 => '错题再练',
            default => throw new InvalidArgumentException("不支持的 assemble_type: {$assembleType}"),
        };
    }

    public static function extractExamCode(string $paperId): string
    {
        preg_match('/paper_(\d{15})/', $paperId, $matches);
        $examCode = $matches[1] ?? '';

        if ($examCode === '') {
            $digits = preg_replace('/[^0-9]/', '', $paperId);
            $examCode = substr(str_pad($digits, 15, '0', STR_PAD_LEFT), -15);
        }

        if (!PaperIdGenerator::validate($examCode)) {
            throw new InvalidArgumentException("无效的考试编码: {$paperId}");
        }

        return $examCode !== '' ? $examCode : $paperId;
    }

    public static function buildPaperDisplayTitle(string $studentName, string $paperId, int $assembleType): string
    {
        $prefix = self::buildPaperPrefix($studentName, $paperId, $assembleType);
        $date = now()->format('Ymd');

        return "{$prefix}_{$date}";
    }

    public static function buildPaperPrefix(string $studentName, string $paperId, int $assembleType): string
    {
        $examCode = self::extractExamCode($paperId);
        $label = self::assembleTypeLabel($assembleType);

        return "{$studentName}_{$examCode}_{$label}";
    }

    public static function buildPaperDisplayTitleWithStamp(string $studentName, string $paperId, int $assembleType, string $stamp): string
    {
        $prefix = self::buildPaperPrefix($studentName, $paperId, $assembleType);

        return "{$prefix}_{$stamp}";
    }

    public static function buildPdfTitle(string $studentName, string $paperId, int $assembleType, string $kind): string
    {
        return self::buildPaperDisplayTitle($studentName, $paperId, $assembleType)."_{$kind}";
    }

    public static function toSafeFilename(string $name, int $maxLength = 120): string
    {
        $safe = preg_replace('/[\\\\\\/\\:\\*\\?\\\"\\<\\>\\|\\s]+/u', '_', trim($name));
        $safe = preg_replace('/_+/u', '_', (string) $safe);
        $safe = trim((string) $safe, '._');

        if ($safe === '') {
            $safe = 'paper';
        }

        if (mb_strlen($safe) > $maxLength) {
            $safe = mb_substr($safe, 0, $maxLength);
        }

        return $safe;
    }
}
