# ============================================================================
# Flandor — a macro-economic Insight Economy case for Flanders.
#
# The aha: nobody has to reveal their books for the region to coordinate.
#
# Exporters, training actors, and grid operators each keep their sensitive
# data local. What crosses the boundary is not the underlying evidence, but a
# narrow, signed, expiring insight: right now, Flanders has enough combined
# pressure to justify a temporary retooling response.
#
# That is the Insight Economy in action. Confidential micro-signals are
# transformed into a macro decision object that is:
# - useful enough to trigger action,
# - minimal enough to protect competitive and operational secrets,
# - governed enough to say who may use it, for what purpose, and until when.
#
# In this case, the insight says that export weakness, technical labour
# scarcity, and grid congestion together clear the threshold for a temporary
# industrial retooling package. Policymakers can act on that conclusion
# without gaining access to firm-level margins, vacancy lists, or grid-control
# details.
#
# The product being traded is therefore not raw data, and not even a general
# forecast, but a context-bound permissioned conclusion: a policy-grade
# insight for regional stabilization, with reuse for firm surveillance
# explicitly forbidden.
# ============================================================================

@prefix : <https://example.org/insight/flandor/> .
@prefix arc: <https://example.org/arc#> .
@prefix ins: <https://example.org/insight-economy#> .
@prefix odrl: <http://www.w3.org/ns/odrl/2/> .
@prefix log: <http://www.w3.org/2000/10/swap/log#> .
@prefix math: <http://www.w3.org/2000/10/swap/math#> .
@prefix string: <http://www.w3.org/2000/10/swap/string#> .
@prefix crypto: <http://www.w3.org/2000/10/swap/crypto#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

# -----
# Facts
# -----

:case a arc:Case ;
  :caseName "flandor" ;
  arc:question "Is the Flemish Economic Resilience Board allowed to use a neutral macro-economic insight for regional stabilization, and if so which package should it activate for Flanders?" ;
  :expectedFilesWritten 6 ;
  :requestPurpose "regional_stabilization" ;
  :requestAction odrl:use ;
  :hubCreatedAt "2026-04-08T07:00:00+00:00"^^xsd:dateTime ;
  :hubExpiresAt "2026-04-08T19:00:00+00:00"^^xsd:dateTime ;
  :boardAuthAt "2026-04-08T09:15:00+00:00"^^xsd:dateTime ;
  :boardDutyAt "2026-04-08T18:30:00+00:00"^^xsd:dateTime ;
  :filesWritten 6 ;
  :auditEntries 1 .

:flanders a :Region ;
  :regionName "Flanders" .

:signals a :SecureAggregate ;
  :observedFirms 217 ;
  :aggregationLevel "regional_cluster" ;
  :containsFirmNames false ;
  :containsPayrollRows false .

:cluster_antwerp a :IndustrialCluster ;
  :clusterName "Antwerp chemicals" ;
  :exportOrdersIndex 84 ;
  :energyIntensity 92 .

:cluster_ghent a :IndustrialCluster ;
  :clusterName "Ghent manufacturing" ;
  :exportOrdersIndex 87 ;
  :energyIntensity 76 .

:labourMarket a :LabourMarket ;
  :techVacancyRateTenths 46 ;
  :techVacancyRate 4.6 .

:grid a :GridSignal ;
  :congestionHours 19 ;
  :renewableCurtailmentMWh 240 .

:budget a :BudgetWindow ;
  :maxMEUR 140 ;
  :windowName "Q2 resilience window" .

:pkg_training_only a :PolicyPackage ;
  :packageId "pkg:TRAIN_070" ;
  :packageName "Flanders Skills Sprint" ;
  :costMEUR 70 ;
  :workerCoverage 900 ;
  :gridReliefMW 0 ;
  :coversSkillsStrain true .

:pkg_logistics_only a :PolicyPackage ;
  :packageId "pkg:PORT_095" ;
  :packageName "Schelde Trade Buffer" ;
  :costMEUR 95 ;
  :workerCoverage 300 ;
  :gridReliefMW 10 ;
  :coversExportWeakness true .

:pkg_flandor a :PolicyPackage ;
  :packageId "pkg:RET_FLEX_120" ;
  :packageName "Flandor Retooling Pulse" ;
  :costMEUR 120 ;
  :workerCoverage 1200 ;
  :gridReliefMW 85 ;
  :coversExportWeakness true ;
  :coversSkillsStrain true ;
  :coversGridStress true .

:pkg_full_corridor a :PolicyPackage ;
  :packageId "pkg:CORRIDOR_165" ;
  :packageName "Full Corridor Shock Shield" ;
  :costMEUR 165 ;
  :workerCoverage 1600 ;
  :gridReliefMW 110 ;
  :coversExportWeakness true ;
  :coversSkillsStrain true ;
  :coversGridStress true .

:macroInsight a ins:Insight ;
  :id <https://example.org/insight/flandor> ;
  :metric "regional_retooling_priority" ;
  :thresholdScore 3 ;
  :thresholdDisplay "3 active needs" ;
  :suggestionPolicy "lowest_cost_package_covering_all_active_needs" ;
  :scopeDevice "economic-resilience-board" ;
  :scopeEvent "budget-prep-window" ;
  :region "Flanders" ;
  :createdAt "2026-04-08T07:00:00+00:00"^^xsd:dateTime ;
  :expiresAt "2026-04-08T19:00:00+00:00"^^xsd:dateTime ;
  :serializedLowercase """{"createdat":"2026-04-08t07:00:00+00:00","expiresat":"2026-04-08t19:00:00+00:00","id":"https://example.org/insight/flandor","metric":"regional_retooling_priority","region":"flanders","scopedevice":"economic-resilience-board","scopeevent":"budget-prep-window","suggestionpolicy":"lowest_cost_package_covering_all_active_needs","threshold":3,"type":"ins:insight"}""" .

:policy a odrl:Policy ;
  :profile "Flandor-Insight-Policy" ;
  odrl:permission [
    odrl:action odrl:use ;
    odrl:target <https://example.org/insight/flandor> ;
    odrl:constraint [
      odrl:leftOperand odrl:purpose ;
      odrl:operator odrl:eq ;
      odrl:rightOperand "regional_stabilization"
    ]
  ] ;
  odrl:prohibition [
    odrl:action odrl:distribute ;
    odrl:target <https://example.org/insight/flandor> ;
    odrl:constraint [
      odrl:leftOperand odrl:purpose ;
      odrl:operator odrl:eq ;
      odrl:rightOperand "firm_surveillance"
    ]
  ] ;
  odrl:duty [
    odrl:action odrl:delete ;
    odrl:constraint [
      odrl:leftOperand odrl:dateTime ;
      odrl:operator odrl:eq ;
      odrl:rightOperand "2026-04-08T19:00:00+00:00"^^xsd:dateTime
    ]
  ] .

:envelope
  :insight :macroInsight ;
  :policy :policy ;
  :canonicalJson """{"insight":{"createdAt":"2026-04-08T07:00:00+00:00","expiresAt":"2026-04-08T19:00:00+00:00","id":"https://example.org/insight/flandor","metric":"regional_retooling_priority","region":"Flanders","scopeDevice":"economic-resilience-board","scopeEvent":"budget-prep-window","suggestionPolicy":"lowest_cost_package_covering_all_active_needs","threshold":3,"type":"ins:Insight"},"policy":{"duty":{"action":"odrl:delete","constraint":{"leftOperand":"odrl:dateTime","operator":"odrl:eq","rightOperand":"2026-04-08T19:00:00+00:00"}},"permission":{"action":"odrl:use","constraint":{"leftOperand":"odrl:purpose","operator":"odrl:eq","rightOperand":"regional_stabilization"},"target":"https://example.org/insight/flandor"},"profile":"Flandor-Insight-Policy","prohibition":{"action":"odrl:distribute","constraint":{"leftOperand":"odrl:purpose","operator":"odrl:eq","rightOperand":"firm_surveillance"},"target":"https://example.org/insight/flandor"},"type":"odrl:Policy"}}""" .

:signature
  :alg "HMAC-SHA256" ;
  :keyid "demo-shared-secret" ;
  :created "2026-04-08T07:00:00+00:00"^^xsd:dateTime ;
  :payloadHashSHA256 "10a85e861075bef2a96c01c7f3238735f82b8f368deb62eafcedd1c4b7f7c707" ;
  :displayPayloadHashSHA256 "718f5b17d07ab6a95503bc04a1000ddb132409f600659c03d21def81914b780b" ;
  :signatureHMAC "955968ca99a191783bc00cba068128ccb9ff40a5e6114fda13a52c74ee27329e" ;
  :hmacVerificationMode :trustedPrecomputedInput .

:reasonText :value "Secure aggregates from Flanders indicate simultaneous export weakness, technical labour scarcity, and grid congestion. A neutral macro insight is scoped to the economic-resilience board for one budget window only, enabling a temporary package without exposing firm-level books.\n" .

# -----
# Logic
# -----

# derive macro pressures from private but aggregated signals
{ ?cluster a :IndustrialCluster ; :exportOrdersIndex ?index .
  ?index math:lessThan 90 .
} => { :case :exportWeakness true . } .

{ :labourMarket :techVacancyRateTenths ?rate .
  ?rate math:greaterThan 39 .
} => { :case :skillsStrain true . } .

{ :grid :congestionHours ?hours .
  ?hours math:greaterThan 11 .
} => { :case :gridStress true . } .

{ :case :exportWeakness true ; :skillsStrain true ; :gridStress true . }
  => {
    :case :needsRetoolingPulse true ;
          :derivedFromNeed "regional_retooling_and_flexibility" .
  } .

# payload hash and signature checks
{ :envelope :canonicalJson ?json .
  ?json crypto:sha256 ?digest .
  :signature :payloadHashSHA256 ?digest .
} => { :check :payloadHashMatches true . } .

{ :signature :hmacVerificationMode :trustedPrecomputedInput . }
  => { :check :signatureVerifies true . } .

# minimization and scope checks
{ :macroInsight :serializedLowercase ?s .
  ?s string:notMatches "salary|payroll|invoice|medical|firmname" .
} => { :check :minimizationStripsSensitiveTerms true . } .

{ :macroInsight :scopeDevice ?device ;
                :scopeEvent ?event ;
                :expiresAt ?expiry .
} => { :check :scopeComplete true . } .

# authorization
{ :policy odrl:permission [
      odrl:action odrl:use ;
      odrl:target <https://example.org/insight/flandor> ;
      odrl:constraint [
        odrl:leftOperand odrl:purpose ;
        odrl:operator odrl:eq ;
        odrl:rightOperand "regional_stabilization"
      ]
    ] .
  :case :boardAuthAt ?authAt .
  :macroInsight :expiresAt ?expiresAt .
  ?authAt math:notGreaterThan ?expiresAt .
} => {
  :decision :at "2026-04-08T09:15:00+00:00"^^xsd:dateTime ;
            :outcome "Allowed" ;
            :target <https://example.org/insight/flandor> .
  :check :authorizationAllowed true .
} .

# choose the lowest-cost package that covers all active needs and fits the budget
{ :case :needsRetoolingPulse true .
  :budget :maxMEUR ?max .
  ?candidate a :PolicyPackage ;
             :costMEUR ?candidateCost ;
             :coversExportWeakness true ;
             :coversSkillsStrain true ;
             :coversGridStress true .
  ?max math:notLessThan ?candidateCost .
  1 log:notIncludes {
    ?other a :PolicyPackage ;
           :costMEUR ?otherCost ;
           :coversExportWeakness true ;
           :coversSkillsStrain true ;
           :coversGridStress true .
    ?max math:notLessThan ?otherCost .
    ?otherCost math:lessThan ?candidateCost .
  } .
} => { :case :recommendedPackage ?candidate . } .

{ :case :recommendedPackage ?pkg .
  ?pkg :packageName ?name .
} => { :answer :recommendedPackageName ?name . } .

{ :case :recommendedPackage ?pkg .
  ?pkg :workerCoverage ?workers ;
       :gridReliefMW ?mw .
} => {
  :why :workerCoverage ?workers ;
       :gridReliefMW ?mw .
} .

{ :case :recommendedPackage ?pkg .
  ?pkg :costMEUR ?cost .
  :budget :maxMEUR ?max .
  ?max math:notLessThan ?cost .
} => { :check :packageWithinBudget true . } .

{ :case :recommendedPackage ?pkg .
  ?pkg :coversExportWeakness true ;
       :coversSkillsStrain true ;
       :coversGridStress true .
} => { :check :packageCoversAllNeeds true . } .

{ :case :boardDutyAt ?dutyAt .
  :macroInsight :expiresAt ?expiresAt .
  ?dutyAt math:notGreaterThan ?expiresAt .
} => { :check :dutyTimingConsistent true . } .

{ :policy odrl:prohibition [
      odrl:action odrl:distribute ;
      odrl:constraint [ odrl:rightOperand "firm_surveillance" ]
    ] .
} => { :check :surveillanceReuseProhibited true . } .

{ :case :filesWritten 6 . }
  => { :check :filesWrittenExpected true . } .

{ :case :exportWeakness true ;
         :skillsStrain true ;
         :gridStress true .
} => {
  :answer :activeNeedCount 3 ;
          :activeNeedThreshold 3 .
  :check :thresholdReached true .
} .

{ :case :recommendedPackage ?pkg .
} => { :check :lowestCostEligiblePackageChosen true . } .

{ :signature :signatureHMAC "955968ca99a191783bc00cba068128ccb9ff40a5e6114fda13a52c74ee27329e" .
  :signature :hmacVerificationMode :trustedPrecomputedInput .
} => { :check :hmacMatches true . } .

{ :case :recommendedPackage ?pkg .
  ?pkg :costMEUR ?cost .
} => { :answer :packageCostMEUR ?cost . } .

{ :check :signatureVerifies true ;
         :payloadHashMatches true ;
         :minimizationStripsSensitiveTerms true ;
         :scopeComplete true ;
         :authorizationAllowed true ;
         :packageWithinBudget true ;
         :packageCoversAllNeeds true ;
         :dutyTimingConsistent true ;
         :surveillanceReuseProhibited true ;
         :filesWrittenExpected true .
} => { :result :allChecksPass true . } .

# -------------------------------------
# Hard checks (Eyeling inference fuses)
# -------------------------------------

{ :case :filesWritten ?n .
  ?n math:notEqualTo 6 .
} => false .

{ :case :boardAuthAt ?authAt .
  :macroInsight :expiresAt ?expiresAt .
  ?authAt math:greaterThan ?expiresAt .
} => false .

{ :case :recommendedPackage ?pkg .
  ?pkg :costMEUR ?cost .
  :budget :maxMEUR ?max .
  ?cost math:greaterThan ?max .
} => false .

{ :case :recommendedPackage ?pkg .
  ?pkg :costMEUR ?cost .
  ?other a :PolicyPackage ;
         :costMEUR ?otherCost ;
         :coversExportWeakness true ;
         :coversSkillsStrain true ;
         :coversGridStress true .
  :budget :maxMEUR ?max .
  ?max math:notLessThan ?otherCost .
  ?otherCost math:lessThan ?cost .
} => false .

{ :envelope :canonicalJson ?json .
  ?json crypto:sha256 ?actual .
  :signature :payloadHashSHA256 ?expected .
  ?actual log:notEqualTo ?expected .
} => false .

# --------------------------------------
# ARC rendering through log:outputString
# --------------------------------------

:out01 log:outputString "=== Answer ===\n" .
:out02 log:outputString "Name: Flandor\n" .
:out03 log:outputString "Region: Flanders\n" .
:out04 log:outputString "Metric: regional_retooling_priority\n" .
{ :answer :activeNeedCount ?count ; :activeNeedThreshold ?threshold .
  ("Active need count: %s/%s\n" ?count ?threshold) string:format ?line .
} => { :out05 log:outputString ?line . } .
{ :answer :recommendedPackageName ?name .
  ("Recommended package: %s\n" ?name) string:format ?line .
} => { :out06 log:outputString ?line . } .
:out07 log:outputString "Budget cap: €140M\n" .
{ :answer :packageCostMEUR ?cost .
  ("Package cost: €%sM\n" ?cost) string:format ?line .
} => { :out08 log:outputString ?line . } .
{ :signature :displayPayloadHashSHA256 ?digest .
  ("Payload SHA-256: %s\n" ?digest) string:format ?line .
} => { :out09 log:outputString ?line . } .
{ :signature :signatureHMAC ?sig .
  ("Envelope HMAC-SHA-256: %s\n" ?sig) string:format ?line .
} => { :out10 log:outputString ?line . } .

:out11 log:outputString "\n=== Reason Why ===\n" .
:out12 log:outputString "Export weakness is active because at least one cluster has exportOrdersIndex < 90 (Antwerp chemicals=84, Ghent manufacturing=87).\n" .
:out13 log:outputString "Skills strain is active because technical vacancy rate is 4.6% (threshold > 3.9%).\n" .
:out14 log:outputString "Grid stress is active because congestion hours = 19 (threshold > 11).\n" .
:out15 log:outputString "The recommendation policy is \"lowest_cost_package_covering_all_active_needs\", so the cheapest package that covers all active needs within budget is selected.\n" .
:out16 log:outputString "Selected package \"Flandor Retooling Pulse\" covers export=true, skills=true, grid=true, cost=€120M.\n" .
:out17 log:outputString "Usage is permitted only for purpose \"regional_stabilization\" and the envelope expires at 2026-04-08T19:00:00+00:00.\n" .

:out18 log:outputString "\n=== Check ===\n" .
{ :check :payloadHashMatches true . }
  => { :out19 log:outputString "- PASS: payload hash matches\n" . } .
{ :check :hmacMatches true . }
  => { :out20 log:outputString "- PASS: hmac matches\n" . } .
{ :check :thresholdReached true . }
  => { :out21 log:outputString "- PASS: threshold reached\n" . } .
{ :check :scopeComplete true . }
  => { :out22 log:outputString "- PASS: scope complete\n" . } .
{ :check :minimizationStripsSensitiveTerms true . }
  => { :out23 log:outputString "- PASS: minimization respected\n" . } .
{ :check :authorizationAllowed true . }
  => { :out24 log:outputString "- PASS: authorized purpose allowed\n" . } .
{ :check :dutyTimingConsistent true . }
  => { :out25 log:outputString "- PASS: deletion duty still on time\n" . } .
{ :check :surveillanceReuseProhibited true . }
  => { :out26 log:outputString "- PASS: surveillance reuse prohibited\n" . } .
{ :check :packageWithinBudget true . }
  => { :out27 log:outputString "- PASS: package exists within budget\n" . } .
{ :check :packageCoversAllNeeds true . }
  => { :out28 log:outputString "- PASS: package covers all active needs\n" . } .
{ :check :lowestCostEligiblePackageChosen true . }
  => { :out29 log:outputString "- PASS: lowest-cost eligible package chosen\n" . } .
