# SPDX-License-Identifier: LSL-1.0
# Copyright (c) 2026 Markus Maiwald
# Stewardship: Self Sovereign Society Foundation
#
# This file is part of the Nexus Sovereign Core.
# See legal/LICENSE_SOVEREIGN.md for license terms.

## NIP Shell Core Types
##
## This module defines the foundational data structures for the NIP shell
## interface, including sessions, transactions, and shell-specific types.

import std/[times, tables, options, json]
import types_fixed

# =============================================================================
# Content Identifier (CID) Types
# =============================================================================

type
  CID* = object
    ## Content Identifier using BLAKE3 hash
    hash*: string
    algorithm*: string  # "blake3", "blake2b", etc.

  VariantFingerprint* = object
    ## Unique identifier for a package variant
    cid*: CID
    packageId*: PackageId
    buildFlags*: seq[string]
    features*: seq[string]
    timestamp*: DateTime

proc `$`*(cid: CID): string =
  result = cid.algorithm & ":" & cid.hash[0..11] & "..."

proc `$`*(vf: VariantFingerprint): string =
  result = $vf.packageId & "@" & $vf.cid

# =============================================================================
# Session Context and State
# =============================================================================

type
  SessionContext* = object
    ## Current shell session state
    track*: string              # Current track (stable, testing, dev)
    channels*: seq[string]      # Preferred channels in order
    flavor*: string             # OS flavor (nexusos, nexusbsd, etc.)
    toolchain*: string          # Build toolchain version
    policy*: Table[string, string]  # Session policies
    workingDir*: string         # Current working directory
    transactionId*: Option[string]  # Active transaction ID
    created*: DateTime
    lastUsed*: DateTime

  SessionMetadata* = object
    ## Metadata for saved sessions
    name*: string
    description*: string
    created*: DateTime
    lastUsed*: DateTime
    size*: int64  # Approximate size in bytes

# =============================================================================
# Transaction Types
# =============================================================================

type
  TransactionState* = enum
    Planning, Staged, Committed, RolledBack, Failed

  TransactionPlan* = object
    ## Plan for a transaction before execution
    id*: string
    packages*: seq[VariantFingerprint]
    dependencies*: seq[VariantFingerprint]
    conflicts*: seq[string]
    estimatedSize*: int64
    estimatedTime*: int
    securityImpact*: string
    created*: DateTime

  Transaction* = object
    ## Active or completed transaction
    id*: string
    plan*: TransactionPlan
    state*: TransactionState
    startTime*: DateTime
    endTime*: Option[DateTime]
    rollbackPoint*: Option[string]
    errorMessage*: Option[string]

# =============================================================================
# Integrity and Attestation Types
# =============================================================================

type
  IntegrityState* = enum
    Verified,      # Matches expected hash
    UserModified,  # User has modified files
    Tampered       # Unauthorized changes detected

  IntegrityStatus* = object
    ## Integrity status for a package variant
    variant*: VariantFingerprint
    state*: IntegrityState
    lastChecked*: DateTime
    modifiedFiles*: seq[string]
    suspiciousActivity*: seq[string]

  AttestationLevel* = enum
    None, Basic, Enhanced, Judicial

  Attestation* = object
    ## Cryptographic attestation for a package
    variant*: VariantFingerprint
    level*: AttestationLevel
    signatures*: seq[string]  # Base64 encoded signatures
    witnesses*: seq[string]   # Witness signatures
    timestamp*: DateTime
    expires*: Option[DateTime]

# =============================================================================
# Shell Command Types
# =============================================================================

type
  CommandResult* = object
    ## Result of executing a shell command
    success*: bool
    output*: string
    error*: string
    duration*: float  # seconds
    timestamp*: DateTime

  ShellPromptInfo* = object
    ## Information for generating the shell prompt
    track*: string
    integrity*: IntegrityState
    transactionActive*: bool
    transactionId*: Option[string]
    workingDir*: string

# =============================================================================
# Registry and Database Types
# =============================================================================

type
  RegistryEntry* = object
    ## Entry in the package registry
    variant*: VariantFingerprint
    location*: string  # CAS path
    size*: int64
    installed*: DateTime
    lastUsed*: DateTime
    attestation*: Option[Attestation]
    integrity*: IntegrityStatus

# =============================================================================
# Utility Functions
# =============================================================================

proc newCID*(hash: string, algorithm: string = "blake3"): CID =
  CID(hash: hash, algorithm: algorithm)

proc newSessionContext*(): SessionContext =
  let now = now()
  SessionContext(
    track: "stable",
    channels: @["main", "community"],
    flavor: "nexusos",
    toolchain: "latest",
    policy: initTable[string, string](),
    workingDir: "/",
    created: now,
    lastUsed: now
  )

proc newTransactionPlan*(id: string): TransactionPlan =
  TransactionPlan(
    id: id,
    packages: @[],
    dependencies: @[],
    conflicts: @[],
    created: now()
  )

proc isActive*(transaction: Transaction): bool =
  transaction.state in {Planning, Staged}

proc isComplete*(transaction: Transaction): bool =
  transaction.state in {Committed, RolledBack, Failed}