#!/usr/bin/php
<?php

/*
 * The MIT License
 *
 * Copyright 2021 Austrian Centre for Digital Humanities.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#use RuntimeException;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\ClientException;
use EasyRdf\Graph;
use EasyRdf\Resource;
use EasyRdf\Literal;
use zozlak\argparse\ArgumentParser as AP;
use acdhOeaw\UriNormalizer;
use acdhOeaw\arche\lib\Schema;
use acdhOeaw\arche\refSources\NamedEntityIteratorFile;
use acdhOeaw\arche\refSources\NamedEntityIteratorRepo;
use acdhOeaw\arche\refSources\NamedEntityInterface;

if (file_exists(__DIR__ . '/../../autoload.php')) {
    require_once __DIR__ . '/../../autoload.php';
} else {
    require_once __DIR__ . '/vendor/autoload.php';
}

const MODE_RESOLVE = 1;
const MODE_PARSE = 2;
const MODE_TEST = 3;
const MODE_UPDATE = 4;

$modes       = [
    'resolve' => MODE_RESOLVE,
    'parse'   => MODE_PARSE,
    'test'    => MODE_TEST,
    'update'  => MODE_UPDATE,
];
$parser      = new AP("Enriches metadata by fetching additional information from external reference sources (GND, geonames, etc.)\nWhich resource classes are processed, which external reference sources are used and which properties are fetched from them is driven by the configuration file.");
$parser->addArgument('--limit', type: AP::TYPE_INT, default: PHP_INT_MAX, help: 'limit number of processed resources');
$parser->addArgument('--after', help: 'process only resources modified after a given date');
$parser->addArgument('--id', help: 'process only repository resource with a given id');
$parser->addArgument('--repoUrl', help: 'use a given repository instance (overwrites the `repositoryUrl` property read from the config file)');
$parser->addArgument('--inputFile', help: 'read resources from a given RDF file instead of the ARCHE repository');
$parser->addArgument('--idProp', help: '(needed only when --inputFile is used and ARCHE repository URL is unknown) RDF property storing resource identifiers.');
$parser->addArgument('--user', help: 'user name used for repository authentication (not important if --test or --resolveOnly are used)');
$parser->addArgument('--pswd', help: 'password used for repository authentication (not important if --test or --resolveOnly are used)');
$parser->addArgument('--mode', default: 'parse', choices: array_keys($modes), help: "operation mode\n    - resolve - only try to resolve the external URI (finds broken external URIs)\n    - parse [default] - resolve the external URI and parse the output (when used with --verbose and/or --output it allows to inspect the data provided by the external source and test the metadata mapping defined in the configuration file)\n    - test - tries to update the repository resource with data fetched from the external source (so doorkeeper checks are performed) but rolls back the update no matter if it was successful or not\n    - update - updates the repository resource with data fetched from the external source\n");
$parser->addArgument('--verbose', action: AP::ACTION_STORE_TRUE, help: 'provide more verbose output, especially print the data fetched from the external reference source');
$parser->addArgument('--output', help: 'when used, the data to be saved to the repository are also saved in a TTL file');
$parser->addArgument('cfgFile', help: 'path to the configuration file');
$param       = $parser->parseArgs();
$param->mode = $modes[$param->mode];
if (!file_exists($param->cfgFile)) {
    exit("Configuration file " . $param->cfgFile . " doesn't exist\n");
}

// Configuration initialization
$cfg       = json_decode(json_encode(yaml_parse_file($param->cfgFile)));
$cfg->auth = $cfg->auth ?? new stdClass();
if (!empty($param->user) || !isset($cfg->auth->user)) {
    $cfg->auth->user = $param->user;
}
if (!empty($param->pswd) || !isset($cfg->auth->password)) {
    $cfg->auth->password = $param->pswd;
}
if (!empty($param->repoUrl) || !isset($cfg->repositoryUrl)) {
    $cfg->repositoryUrl = $param->repoUrl;
}
$dateFilter = !empty($param->after) ? $param->after : null;

// Helper objects initialization
$normalizer  = UriNormalizer::factory();
$outputGraph = new Graph();
$client      = new Client([
    'http_errors'     => false,
    'allow_redirects' => ['track_redirects' => true]
    ]);
if (!empty($param->inputFile)) {
    $schema = ['id' => $param->idProp];
    $schema = new Schema((object) $schema);
    $source = new NamedEntityIteratorFile($param->inputFile, $cfg->repositoryUrl, $schema, $cfg->auth->user, $cfg->auth->password);
} else {
    $source = new NamedEntityIteratorRepo($cfg->repositoryUrl, $cfg->auth->user, $cfg->auth->password);
}

// Do the job
foreach ($cfg->classes as $class => $cCfg) {
    echo "\n### Processing resources of class $class\n\n";
    foreach ($cCfg as $mCfg) {
        $idFilter = !empty($param->id) ? "^" . $param->id . "$" : "$mCfg->match";
        $source->setFilter($class, $idFilter, $dateFilter, $param->limit);

        // sanitize property config
        foreach ($mCfg->mapping as $pCfg) {
            $pCfg->langRequired = (bool) ($pCfg->langRequired ?? false);
            $pCfg->forceLang    = $pCfg->forceLang ?? '';
            $pCfg->defaultLang  = $pCfg->defaultLang ?? '';
        }

        foreach ($source->getNamedEntities() as $N => $namedEntity) {
            /* @var $namedEntity NamedEntityInterface */
            $N  = $N + 1;
            $T  = $source->getCount();
            $NN = round(100 * $N / $T);
            echo "Resource " . $namedEntity->getUri() . " ($N/$T $NN%)\n";

            $newValues = [];
            $ids       = $namedEntity->getIdentifiers($mCfg->match);
            if (count($ids) === 0) {
                echo "WARNING: no matching identifiers\n";
            }
            foreach ($ids as $id) {
                $url     = str_replace('%id%', $id, $mCfg->resolve);
                $refMeta = fetch($url, $id, $client, $mCfg->format, $mCfg->resolve);
                if ($refMeta === null) {
                    echo "ERROR: Failed to load data from $url\n";
                    continue;
                }
                if (count($refMeta->propertyUris()) === 0) {
                    echo "ERROR: Data fetched from $url doesn't contain the $id resource\n";
                    continue;
                }
                if ($param->mode <= MODE_RESOLVE) {
                    continue;
                }
                $h = fopen('foo', 'a');
                fwrite($h, $refMeta->dump('text'));
                fclose($h);

                foreach ($mCfg->mapping as $pCfg) {
                    if (!isset($newValues[$pCfg->property])) {
                        $newValues[$pCfg->property] = [];
                    }
                    $values = resolve($refMeta, $pCfg->path, $client, $mCfg);
                    $values = filter($values, $pCfg->match ?? null, $pCfg->skip ?? null);
                    foreach ($values as $i) {
                        $lang = '_';
                        switch ($pCfg->type) {
                            case 'id':
                                $i    = $normalizer->normalize((string) $i);
                                break;
                            case 'literal':
                                $lang = (string) ($i instanceof Literal ? $i->getLang() : '');
                                if ($pCfg->forceLang) {
                                    $lang = $pCfg->forceLang;
                                } elseif ($pCfg->langRequired && !empty($pCfg->defaultLang)) {
                                    $lang = $pCfg->defaultLang;
                                }
                                break;
                            case 'resource':
                                break;
                            default:
                                throw new RuntimeException("Unknown property type $pCfg->type");
                        }
                        if (!isset($newValues[$pCfg->property][$lang])) {
                            $newValues[$pCfg->property][$lang] = [];
                        }
                        $maxCountCond = count($newValues[$pCfg->property][$lang]) < ($pCfg->maxPerLang ?? PHP_INT_MAX);
                        $langReqCond  = !empty($lang) || !$pCfg->langRequired;
                        if ($maxCountCond && $langReqCond) {
                            if (empty($lang) && !empty($pCfg->defaultLang ?? '')) {
                                $lang = $pCfg->defaultLang;
                            }
                            $newValues[$pCfg->property][$lang][] = (string) $i;
                        }
                    }
                }
            }
            if ($param->mode <= MODE_RESOLVE) {
                continue;
            }

            $newMeta = (new Graph())->resource($namedEntity->getUri());
            foreach ($newValues as $prop => $langs) {
                foreach ($langs as $lang => $values) {
                    foreach ($values as $n => $value) {
                        if ($lang === '_') {
                            $newMeta->addResource($prop, $value);
                        } else {
                            $newMeta->addLiteral($prop, $value, empty($lang) ? null : $lang);
                        }
                    }
                }
            }
            echo $param->verbose ? $newMeta->dump('text') : '';
            if (!empty($param->output)) {
                $newMeta->copy([], '/^$/', '', $outputGraph);
            }
            if ($param->mode <= MODE_PARSE) {
                continue;
            }
            try {
                $namedEntity->updateMetadata($newMeta, $param->mode <= MODE_TEST);
            } catch (ClientException $ex) {
                echo "ERROR: " . (string) $ex->getResponse()->getBody() . "\n";
            }
        }
    }
}
if (!empty($param->output)) {
    file_put_contents($param->output, $outputGraph->serialise('text/turtle'));
}

function fetch(string $url, string $id, Client $client, string $format,
               string $resolve): ?Resource {
    echo "fetching $id from $url\n";
    $response = $client->send(new Request('get', $url, ['Accept' => $format]));
    if ($response->getStatusCode() !== 200) {
        return null;
    }
    $graph   = new Graph();
    $graph->parse((string) $response->getBody(), $format);
    $refMeta = $graph->resource($id);

    // if there were redirects try to adjust the id based on redirect URLs
    if (count($refMeta->propertyUris()) === 0) {
        $redirectUrl = $response->getHeader('X-Guzzle-Redirect-History');
        $redirectUrl = array_pop($redirectUrl);
        $matchRegex  = "`" . str_replace('%id%', '(.*)', $resolve) . "`";
        $matches     = null;
        preg_match($matchRegex, $redirectUrl, $matches);
        if (count($matches) >= 2) {
            $refMeta = $graph->resource($matches[1]);
        }
    }

    return $refMeta;
}

function resolve(Resource $meta, array $path, Client $client, object $mCfg): array {
    if (count($path) < 2) {
        return $meta->all($path[0]);
    }
    $prop   = array_shift($path);
    $values = [];
    foreach ($meta->allResources($prop) as $res) {
        /* @var $res \EasyRdf\Resource */
        if (count($res->propertyUris()) === 0) {
            $id  = $res->getUri();
            $url = str_replace('%id%', $id, $mCfg->resolve);
            $res = fetch($url, $id, $client, $mCfg->format, $mCfg->resolve);
            if ($res !== null) {
                $values = array_merge($values, resolve($res, $path, $client, $mCfg));
            }
        } else {
            $values = array_merge($values, resolve($res, $path, $client, $mCfg));
        }
    }
    return $values;
}

function filter(array $values, ?string $match, ?string $skip): array {
    if (empty($match) && empty($skip)) {
        return $values;
    }
    $filtered = [];
    $skip     = empty($skip) ? '^$' : $skip;
    foreach ($values as $i) {
        if (preg_match("`$match`", (string) $i) && !preg_match("`$skip`", (string) $i)) {
            $filtered[] = $i;
        }
    }
    return $filtered;
}
