#!/usr/bin/env php
<?php

use app\CliUtil;
use app\foreignone\Post;
use app\foreignone\PostLanguage;
use app\foreignone\Upload;

require_once __DIR__.'/../src/init.php';

$options = getInput();
$content = [];
$langs = ['ru', 'en'];
foreach ($langs as $lang) {
    checkFile($options[$lang]);
    $content[$lang] = processImages(file_get_contents($options[$lang]));
}

$post = Post::add([
    'keywords' => '',
    'visible' => false,
    'short_name' => $options['short-name'],
    'date' => '2025-01-01',
    'source_url' => '',
]);
if (!$post)
    CliUtil::die("failed to create post");

foreach ($langs as $lang) {
    $text = $post->addText(
        lang: PostLanguage::from($lang),
        title: $options[$lang.'-title'],
        md: $content[$lang],
        keywords: '',
        toc: false);
    if (!$text) {
        Post::delete($post);
        CliUtil::die("failed to create post text");
    }
}

echo "done\n";
exit(0);


function getInput() {
    global $argv;

    $usage = "usage: $argv[0] --ru ./ru.txt --en ./en.txt --ru-title TITLE --en-title TITLE --short-name NAME\n";
    $option_names = ['ru', 'en', 'ru-title', 'en-title', 'short-name'];
    $options = getopt('', array_map(fn($o) => $o.':', $option_names));
    foreach ($option_names as $option_name) {
        if (!isset($options[$option_name])) {
            fwrite(STDERR, "error: missing option '$option_name'\n");
            fwrite(STDERR, $usage);
            exit(1);
        }
    }
    return $options;
}

function checkFile($file) {
    if (!file_exists($file)) {
        fwrite(STDERR, "error: file $file does not exist\n");
        exit(1);
    }
}

function processImages($md) {
    return preg_replace_callback(
        '/!\[.*?]\((https?:\/\/[^\s)]+)\)/',
        function ($matches) {
            $url = $matches[1];

            $parsed_url = parse_url($url);
            $clean_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'];

            $upload = Upload::getUploadBySourceUrl($clean_url);
            if (!$upload) {
                $name = basename($clean_url);
                $ext = extension($clean_url);
                $tmp = sys_get_temp_dir().'/'.uniqid(rand(), true).'.'.$ext;
                if (!copy($clean_url, $tmp)) {
                    logError('failed to download '.$clean_url.' to '.$tmp);
                    return $matches[0];
                }
                $upload_id = Upload::add($tmp, $name, source_url: $clean_url);
                $upload = Upload::get($upload_id);
                // $tmp file has already been deleted by uploads::add() at this point
            } else {
                logDebug('found existing upload with source_url='.$clean_url);
            }

            return $upload->getMarkdown('align=center');
        },
        $md
    );
}