<?php
# ref https://gist.github.com/furyutei/f7e407fe4b83fd45ef5efbd64ae1a70e
$file = new SplFileObject($argv[1]);
$file->setFlags(SplFileObject::READ_CSV);

$arr = [];
$pages = [];

foreach ($file as $row){
    $page = [];

    $asin = array_shift($row);
    $title = array_shift($row);
    if ($title === "title") {
        continue;
    }
    $detailPageUrl = array_shift($row);
    $webReaderUrl = array_shift($row);
    $productUrl = array_shift($row);

    $acquisitionDate = array_shift($row);
    $time = date_parse_from_format("Y.m.d H:iP", $acquisitionDate);

    $lastAnnotationDate = array_shift($row);
    $percentageRead = array_shift($row);

    $page['title'] = $title;
    $page['lines'] = [
        $title,
        "[web reader $webReaderUrl]",
        "[url $detailPageUrl]",
        "[$productUrl]",
        "",
    ];
    foreach ($row as $a) {
        if (strlen($a) > 0) {
            $page['lines'][] = "[$a]";
        }
    }

    $page['lines'][] = "";
    $page['lines'][] = sprintf("[%s-%s-%s]",$time['year'],$time['month'],$time['day']);

    preg_match_all("/\(([^)]+)\)/",$title,$matches);
    if ($matches[1] !== null) {
        foreach ($matches[1] as $match){
            if (preg_match("/^\d+$/",$match)) {
                continue;
            }
            $page['lines'][] = "[" . $match . "]";
        }
    }

    preg_match_all("/【([^】]+)】/u",$title,$matches);
    if ($matches[1] !== null) {
        foreach ($matches[1] as $match){
            if (preg_match("/^\d+$/",$match)) {
                continue;
            }
            $page['lines'][] = "[" . $match . "]";
        }
    }

    $pages[] = $page;
}

$arr["pages"] = $pages;

echo json_encode($arr);