import marimo

__generated_with = "0.13.15"
app = marimo.App()


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Import modules

        The graph setup, the SHACL check and the JWT signing come from `common.py`,
        the module shared by both worked examples; only the CAP modelling is here.
        """
    )
    return


@app.cell
def _():
    from datetime import datetime, timedelta
    from pathlib import Path

    from dateutil.relativedelta import relativedelta
    from rdflib import RDF, RDFS, BNode, Graph, Literal, Node
    from rdflib.namespace import FOAF, SDO, XSD

    from common import compute_sri, issue_signed_vcs, new_graph, validate_against_cap_shapes
    return (
        BNode,
        FOAF,
        Graph,
        Literal,
        Node,
        Path,
        RDF,
        RDFS,
        SDO,
        XSD,
        compute_sri,
        datetime,
        issue_signed_vcs,
        new_graph,
        relativedelta,
        timedelta,
        validate_against_cap_shapes,
    )


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Pick Eclipse CAP version and defines the others ontologies

        """
    )
    return


@app.cell
def _():
    example = new_graph(cap_version="v0")
    g, CAP, CRED, GX, EX = example.g, example.CAP, example.CRED, example.GX, example.EX
    return (CAP, CRED, EX, GX, g)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Generate an Eclipse `cap:Certification` object

        """
    )
    return


@app.cell
def _(
    BNode,
    CAP,
    EX,
    FOAF,
    GX,
    Graph,
    Literal,
    Node,
    RDF,
    RDFS,
    SDO,
    XSD,
    datetime,
    g,
    relativedelta,
):
    def generate_cap_certification(g: Graph) -> tuple[Node, Node]:
        certification = EX.TrustedNotary_certification01
        g.add((certification, RDF.type, CAP.Certification))
        g.add((certification, CAP.hasObjectOfConformityAssessment, EX.OutScaleSAS_IaaS))

        scheme = BNode()
        g.add((certification, CAP.hasConformityAssessmentScheme, scheme))
        g.add((scheme, RDF.type, CAP.ConformityAssessmentScheme))
        g.add((scheme, RDFS.label, Literal("SecNumCloud")))
        g.add((scheme, RDFS.comment, Literal("version 3.2")))
        issuance_date = datetime(year=2023, month=11, day=30)
        valid_from = issuance_date
        valid_until = valid_from + relativedelta(years=3)
        g.add((certification, CAP.validFrom, Literal(valid_from.isoformat(), datatype=XSD.dateTime)))
        g.add((certification, CAP.validUntil, Literal(valid_until.isoformat(), datatype=XSD.dateTime)))
        g.add((certification, CAP.issuedAt, Literal(issuance_date.isoformat(), datatype=XSD.dateTime)))

        issuer = EX.LNE
        g.add((certification, CAP.issuedBy, issuer))
        g.add((issuer, RDF.type, CAP.ConformityAssessmentBody))
        g.add((issuer, RDF.type, GX.LegalPerson))
        g.add((issuer, FOAF.name, Literal("LABORATOIRE NATIONAL DE METROLOGIE ET D'ESSAIS", lang="fr")))
        g.add((issuer, SDO.vatID, Literal("FR313320244")))

        print(f"The cap:Certification object has the id {certification.n3()}")
        print(f"The cap:Certification issuer is {issuer.n3()}")
        return certification, issuer


    certification, certification_issuer = generate_cap_certification(g)
    return (certification,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Generate the `cred:Evidence` for the Verifiable Credential

        The credential points at the certificate document it transcribes, with a digest
        so a verifier can check that the document behind the claim has not changed.
        The document is the authority's qualification decision, archived in this
        repository under `fixtures/`.
        """
    )
    return


@app.cell
def _(BNode, CRED, Graph, Literal, Node, Path, RDF, compute_sri, g):
    def generate_cred_evidence(g: Graph, evidence_url: str, evidence_file: Path) -> Node:
        evidence = BNode()
        g.add((evidence, RDF.type, CRED.Evidence))
        g.add((evidence, CRED.value, Literal(evidence_url)))
        g.add((evidence, CRED.digest, Literal(f"sha256-{compute_sri(evidence_file)}")))
        return evidence


    # The credential names the archived copy of the authority's decision, which is the only
    # copy that resolves for a machine: the origin answers programmatic requests with a
    # bot-protection page (`HTTP 200`, `content-type: text/html`, 212 bytes) rather than the
    # document. The digest is computed from the same bytes as they sit in the repository, so
    # the two must agree; `docs/notebooks/README.md` records the original source, the
    # retrieval date and the digest.
    evidence = generate_cred_evidence(
        g,
        "https://gitlab.eclipse.org/eclipse/dataspace-cap/dataspace-cap.eclipse.dev/-/raw/main/docs/notebooks/fixtures/2023_2118_np.pdf",
        Path(__file__).parent / "fixtures" / "2023_2118_np.pdf",
    )
    return (evidence,)


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Create the Verifiable Credential

        """
    )
    return


@app.cell
def _(
    CRED,
    EX,
    Literal,
    RDF,
    XSD,
    certification,
    datetime,
    evidence,
    g,
    timedelta,
):
    vc = EX.myvc
    g.add((vc, RDF.type, CRED.VerifiableCredential))
    g.add((vc, CRED.issuer, Literal("did:web:trusted-notary.eu")))
    # Fixed instant: this notebook's output is committed as a generated page,
    # so it must not churn on every regeneration.
    valid_from = datetime(2026, 11, 16, 12, 0, 0)
    valid_until = valid_from + timedelta(days=90)
    g.add((vc, CRED.validFrom, Literal(valid_from.isoformat(), datatype=XSD.dateTime)))
    g.add((vc, CRED.validUntil, Literal(valid_until.isoformat(), datatype=XSD.dateTime)))

    # attach the cap:Certificate to the VC
    g.add((vc, CRED.credentialSubject, certification))

    # attach the cred:Evidence to the VC
    g.add((vc, CRED.evidence, evidence))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Display RDF data in Turtle format

        """
    )
    return


@app.cell
def _(g):
    print(g.serialize(format="ttl"))
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Verify format with SHACL

        """
    )
    return


@app.cell
def _(g, validate_against_cap_shapes):
    validate_against_cap_shapes(g)
    return


@app.cell(hide_code=True)
def _(mo):
    mo.md(
        r"""
        Issue signed Verifiable Credential

        """
    )
    return


@app.cell
def _(CRED, g, issue_signed_vcs):
    issue_signed_vcs(g, CRED)
    return


@app.cell
def _():
    import marimo as mo
    return (mo,)


if __name__ == "__main__":
    app.run()
