xquery version "3.1";

(:~
 : This module provides dictionary annotations for Ahiqar based on
 : Sedra, an online dictionary for the Syriac language.
 :
 : @author Mathias Göbel
 : @version 0.0.0
 : @since 12.2.0
 : @see https://subugoe.pages.gwdg.de/ahiqar/api-documentation/
 : @see https://subugoe.pages.gwdg.de/ahiqar/api-documentation/page/text-api-specs/
 : :)

module namespace sedra="http://ahiqar.uni-goettingen.de/ns/annotations/sedra";

declare namespace tei="http://www.tei-c.org/ns/1.0";

import module namespace commons="http://ahiqar.uni-goettingen.de/ns/commons" at "../commons.xqm";
import module namespace hc="http://expath.org/ns/http-client" at "java:org.expath.exist.HttpClientModule";
import module namespace norm="http://ahiqar.uni-goettingen.de/ns/tapi/txt/normalization" at "../tapi-txt-normalization.xqm";

declare function sedra:main(
    $pages as element(tei:TEI)+,
    $teixml-uri as xs:string,
    $page as xs:string) as map()* {

    commons:debug("SEDRA   → PAGE → " || $page),
    commons:debug("SEDRA   → TEIXMLURI → " || $teixml-uri),

    for $token in $pages//tei:w
    let $id := string($token/@xml:id)
    let $normalizedToken := string($token)
                            => replace("\[|\]", "") (: editorial markup for added text: [ ] :)
                            => norm:get-txt-without-diacritics()
    let $values :=
                    if ($normalizedToken eq "")
                    then ""
                    else
                        (: might return multiple values, each to result in a single annotation :)
                        sedra:get-values($normalizedToken)

    for $value at $pos in $values
    (: do not create an annotation when no normalization is possible (e.g. glyphs) or Sedra returns empty array :)
    where $value ne ""
    return
        map {
            "id": $commons:anno-ns || "/" || $teixml-uri || "/annotation-sedra/" || $id || "/" || $pos,
            "type": "Annotation",
            "body":
                map {
                    "type": "TextualBody",
                    "value": $value,
                    "format": "text/html",
                    "x-content-type": "dictionary"
                },
            "target":
                array {
                    map{
                        "selector": map{
                            "type": "CssSelector",
                            "value": "#" || $id
                        }
                    }
                }
        }
};

declare function sedra:get-values($token as xs:string) as xs:string* {
    let $url :=
                "https://api.ahiqar.d.sub.uni-goettingen.de/sedra-service/syriac/" || string($token)
    let $sedra :=
        hc:send-request(
            <hc:request method="GET" href="{$url}" />
            )[2] => util:binary-to-string() => parse-json()

    for $item in $sedra?* (: iterate over sedra entries (array) for this token :)
    return ((
        (: re-order keys here, if required :)
        for $key in ("gender", "suffixGender", "tense", "category", "stem", "number", "suffixNumber", "person", "kaylo")
        let $target := $item($key)
        where $target ne ""
        return <p><span>{$key}: </span> <span>{$target}</span></p>,

        $item("glosses") ! (
            for $key in map:keys($item("glosses"))
            let $prefix := "gloss (" || $key || "): "
            let $value :=
                (: there are whitespace-only items in the array :)
                string-join($item("glosses")($key)?*[normalize-space(.) ne ""], ", ")
                (: remove html span tags from strings :)
                => replace('<span class="selectableFont">', "")
                => replace('</span>', "")
            (: do not create a gloss when there is no value. :)
            where normalize-space($value) != ("", "&#160;") (: non-breaking spaces for the win :)
            return
                <p><span>{$prefix}</span> <span>{$value}</span></p>
        ),

        $item("lexeme") ! <p><span>Sedra: </span><span><a target="_blank" href="https://sedra.bethmardutho.org/lexeme/get/{$item("lexeme")("id")}">Web 🔗</a>, <a target="_blank" href="{$item("lexeme")("uri")}">API 🔗</a></span></p>

    )  ) => serialize()
};