// Нужные модули
if (!\Bitrix\Main\Loader::includeModule('disk')) { $this->SetVariable('ERR','Модуль Диск недоступен'); return; }
\Bitrix\Main\Loader::includeModule('crm'); // не критично; только для автора

$info = [];
try {
    $root = $this->GetRootActivity();

    // 0) Имя файла берём из Variable1 (готовый шаблон)
    $targetNameRaw = (string)$root->GetVariable('Variable1');
    $info[] = "Шаблон имени из Variable1: " . ($targetNameRaw !== '' ? $targetNameRaw : '—');

    // 1) Источник файла: ТОЛЬКО переменная file (тип Файл)
    $paramVal = $root->GetVariable('file');
    if (empty($paramVal)) {
        throw new \Exception('Переменная file пуста — помести файл в переменную file перед этим шагом');
    }
    $info[] = "Файл взят из переменной file";

    // 2) Превращаем источник в байты + определяем расширение/тип
    $origName = 'file';
    $ext = 'pdf';
    $bytes = null;
    $mime  = 'application/octet-stream';

    if (is_array($paramVal)) {
        if (!empty($paramVal['name'])) {
            $origName = (string)$paramVal['name'];
            $e = pathinfo($origName, PATHINFO_EXTENSION); if ($e) $ext = $e;
        }
        if (!empty($paramVal['content'])) {
            $bytes = $paramVal['content'];
            if (!empty($paramVal['type'])) $mime = (string)$paramVal['type'];
        } elseif (!empty($paramVal['tmp_name'])) {
            $bytes = @file_get_contents($paramVal['tmp_name']);
            if (!empty($paramVal['type'])) $mime = (string)$paramVal['type'];
        } elseif (!empty($paramVal['ID'])) {
            $fa = \CFile::GetFileArray((int)$paramVal['ID']);
            if (is_array($fa)) {
                if (!empty($fa['ORIGINAL_NAME'])) {
                    $origName = (string)$fa['ORIGINAL_NAME'];
                    $e = pathinfo($origName, PATHINFO_EXTENSION); if ($e) $ext = $e;
                }
                if (!empty($fa['SRC'])) {
                    $abs = $_SERVER['DOCUMENT_ROOT'] . $fa['SRC'];
                    $bytes = @file_get_contents($abs);
                }
                if (!empty($fa['CONTENT_TYPE'])) $mime = (string)$fa['CONTENT_TYPE'];
            }
        }
    } elseif (is_int($paramVal) || ctype_digit((string)$paramVal)) {
        $fa = \CFile::GetFileArray((int)$paramVal);
        if (is_array($fa)) {
            if (!empty($fa['ORIGINAL_NAME'])) {
                $origName = (string)$fa['ORIGINAL_NAME'];
                $e = pathinfo($origName, PATHINFO_EXTENSION); if ($e) $ext = $e;
            }
            if (!empty($fa['SRC'])) {
                $abs = $_SERVER['DOCUMENT_ROOT'] . $fa['SRC'];
                $bytes = @file_get_contents($abs);
            }
            if (!empty($fa['CONTENT_TYPE'])) $mime = (string)$fa['CONTENT_TYPE'];
        }
    } elseif (is_string($paramVal)) {
        $origName = basename($paramVal);
        $e = pathinfo($origName, PATHINFO_EXTENSION); if ($e) $ext = $e;
        $bytes = @file_get_contents($paramVal);
    }

    if ($bytes === null || $bytes === false) {
        throw new \Exception('Не удалось прочитать содержимое файла из file');
    }
    $info[] = "Файл получен: исходное имя={$origName}";

    // 3) Автор на Диске (не критично)
    $userId = 1;
    try {
        $docId      = $root->GetDocumentId();
        $docService = \CBPRuntime::GetRuntime()->GetService('DocumentService');
        $docFields  = $docService->GetDocument($docId);
        if (!empty($docFields['ASSIGNED_BY_ID'])) {
            $userId = (int)$docFields['ASSIGNED_BY_ID'];
        } elseif (is_object($GLOBALS['USER']) && method_exists($GLOBALS['USER'],'GetID') && $GLOBALS['USER']->GetID()>0) {
            $userId = (int)$GLOBALS['USER']->GetID();
        }
    } catch (\Throwable $eAuthor) { /* ignore */ }

    // 4) Загружаем на Диск в папку ID_папки
    $folder = \Bitrix\Disk\Folder::loadById(ID_папки);
    if (!$folder) { throw new \Exception('Папка Диска ID_папки не найдена'); }

    /** @var \Bitrix\Disk\File $uploaded */
    $uploaded = $folder->uploadFile(
        ['name' => $origName, 'content' => $bytes],
        ['CREATED_BY' => $userId],
        [],      // rights
        true     // generateUniqueName
    );
    if (!$uploaded || !($uploaded instanceof \Bitrix\Disk\File)) {
        throw new \Exception('Не удалось загрузить файл на Диск');
    }
    $info[] = "Загружено на Диск: DISK_ID=" . $uploaded->getId();

    // 5) Финальное имя: из Variable1; если без расширения — доклеим исходное
    $finalName = trim($targetNameRaw);
    if ($finalName === '') { $finalName = 'file'; }
    $hasExt = (pathinfo($finalName, PATHINFO_EXTENSION) !== '');
    if (!$hasExt) { $finalName .= '.' . ($ext ?: 'pdf'); }

    // Санитария имени (сохраняем расширение)
    $sanitize = static function($s) {
        $basename = $s; $extPart = '';
        $pos = strrpos($s, '.');
        if ($pos !== false) { $basename = substr($s, 0, $pos); $extPart = substr($s, $pos); }
        $basename = preg_replace('~[^\p{L}\p{N}\-_ ]+~u', '', $basename);
        $basename = preg_replace('~\s+~u', '_', $basename);
        return ($basename !== '' ? $basename : 'file') . $extPart;
    };
    $finalName = $sanitize($finalName);

    // Переименовать объект на Диске
    $uploaded->rename($finalName, $userId);
    $info[] = "Переименовано на Диске: {$finalName}";

    // 6) Публичный URL (если не получится — не фатально)
    $publicUrl = '';
    try {
        $extLinks = $uploaded->getExternalLinks([
            'filter' => [
                'OBJECT_ID'  => $uploaded->getId(),
                'CREATED_BY' => $userId,
                'TYPE'       => \Bitrix\Disk\ExternalLink::TYPE_MANUAL,
                '=IS_EXPIRED'=> false,
            ],
            'limit' => 1,
        ]);
        $extLink = is_array($extLinks) ? array_pop($extLinks) : null;
        if (!$extLink) {
            $extLink = $uploaded->addExternalLink([
                'CREATED_BY' => $userId,
                'TYPE'       => \Bitrix\Disk\ExternalLink::TYPE_MANUAL,
            ]);
        }
        if ($extLink && $extLink->getHash()) {
            $publicUrl = \Bitrix\Disk\Driver::getInstance()
                ->getUrlManager()
                ->getShortUrlExternalLink(['hash' => $extLink->getHash(), 'action' => 'default'], true);
            $info[] = "Публичный URL сформирован";
        } else {
            $info[] = "Не удалось получить hash публичной ссылки";
        }
    } catch (\Throwable $eUrl) {
        $info[] = "URL не сформирован: " . $eUrl->getMessage();
    }

    // 7) Результат
    $this->SetVariable('url', $publicUrl ?: '(url недоступен)');
    $this->SetVariable('INFO', implode("; ", $info));
    $this->SetVariable('ERR', '');

} catch (\Throwable $e) {
    $info[] = "Ошибка: " . $e->getMessage();
    $this->SetVariable('ERR', $e->getMessage());
    $this->SetVariable('INFO', implode("; ", $info));
}