// swift-tools-version: 6.2
import Foundation
import PackageDescription

// Build channel, selected at manifest-evaluation time via the NUCLEIC_CHANNEL
// environment variable (dev | canary | beta | rc | stable); defaults to `dev`. It drives two
// things in lockstep:
//   • the app executable's PRODUCT name — which becomes the on-disk binary and
//     therefore the OS process name (Activity Monitor / `ps`):
//        dev -> nucleic-local   canary -> nucleic-canary   beta -> nucleic-beta
//        rc -> nucleic-rc   stable -> nucleic
//   • a compile-time define (`NUCLEIC_STABLE/RC/BETA/CANARY/DEV`) read by NucleicApp for its build
//     identity + warning banner (red local / yellow canary / blue beta / gold release-candidate /
//     none stable), and by NucleicCore's `ContainerManager` to suffix non-release container names.
// Branch mapping (see BUILD.md): dev builds from `dev`, canary from `canary`, beta from `staging`,
// rc from `rc`, stable from `main`.
// TailscaleKit (the embedded tsnet node behind the Tailnet sync transport) has no SwiftPM
// distribution — it's an Xcode framework built from a pinned libtailscale commit by
// scripts/build-tailscalekit.sh into third_party/TailscaleKit/ (untracked, ~100 MB). The
// binary target is declared only when the artifact exists so a fresh clone builds without
// Go/Xcode legwork; NucleicTailnet compiles either way (`#if canImport(TailscaleKit)`) and
// reports "not built in" at runtime when the framework is absent.
let tailscaleKitAvailable = FileManager.default.fileExists(
    atPath: Context.packageDirectory + "/third_party/TailscaleKit/TailscaleKit.xcframework")

let nucleicChannel = (Context.environment["NUCLEIC_CHANNEL"] ?? "dev").lowercased()
let (appProductName, channelDefine): (String, String) = {
    switch nucleicChannel {
    case "stable", "prod", "release": return ("nucleic", "NUCLEIC_STABLE")
    case "rc", "candidate": return ("nucleic-rc", "NUCLEIC_RC")
    case "beta": return ("nucleic-beta", "NUCLEIC_BETA")
    case "canary": return ("nucleic-canary", "NUCLEIC_CANARY")
    default: return ("nucleic-local", "NUCLEIC_DEV")
    }
}()

// The Linux build (docs/ANTIMATTER_RUNNER.md §9, docs/CLOUD_RUNTIME.md Phase 2): the headless
// `nucleicd` runner host compiles for Linux with the Apple-only surface gated out — no SwiftUI
// app or spikes, no Apple containerization (the cloud container IS the sandbox;
// `RunSpec.container` stays nil), CryptoKit backed by swift-crypto inside NucleicProtocol.
// `#if os(Linux)` here runs at manifest-evaluation time on the build machine. The Apple-only
// *package dependencies* stay declared on Linux so dependency resolution (and Package.resolved)
// is identical on every platform; their products are simply never linked there.
#if os(Linux)
let onLinux = true
#else
let onLinux = false
#endif

// The macOS cockpit + its build plugin, the de-risking spikes, and the iOS projection library —
// none of which compile (or make sense) on Linux. Declared out-of-line so the cross-platform
// target list below stays readable.
let darwinOnlyTargets: [Target] = [
    .executableTarget(
        name: "NucleicApp",
        dependencies: [
            "NucleicCore",
            .product(name: "SwiftTerm", package: "SwiftTerm"),
            // Auto-update for direct (non-App-Store) distribution. macOS-only.
            .product(name: "Sparkle", package: "Sparkle"),
        ],
        swiftSettings: [.define(channelDefine)],
        // FoundationModels ships in macOS 26, but its Swift ABI is still shifting between the
        // 26/27 beta seeds: a symbol present in the SDK we build against (e.g.
        // `Generable.promptRepresentation`, emitted by the `@Generable` guided-generation code
        // in AppleIntelligence.swift) can be ABSENT from an older seed's framework. Strong-linked
        // (the Swift autolink default), that makes dyld abort BEFORE main() on any Mac whose seed
        // lacks the symbol — "Symbol not found … FoundationModels", EXC_CRASH / Namespace DYLD —
        // even though every use is already gated behind `#available` + `model.isAvailable`, since
        // those runtime guards never get to run. Weak-linking binds a missing symbol to NULL at
        // load instead of aborting, so the app always launches and the guards do their job (the
        // soft-AI features fall back to their heuristics). Verify the flag took with
        // `otool -l <binary> | grep -A3 FoundationModels` → expect LC_LOAD_WEAK_DYLIB.
        linkerSettings: [
            .unsafeFlags(["-Xlinker", "-weak_framework", "-Xlinker", "FoundationModels"]),
        ],
        plugins: ["EmbedGitCommit"]),
    // Prebuild plugin: stamps the built-from commit into a generated `GitCommit.swift`
    // at build time, so the hash is baked into the binary (correct even on a
    // packaged beta / rc / stable archive, where git isn't present at runtime).
    .plugin(name: "EmbedGitCommit", capability: .buildTool()),
    // Adapter-contract test stubs (fed to NucleicCoreTests). Darwin-only: they lean on
    // Foundation surfaces corelibs doesn't ship (`FileHandle.bytes`).
    .executableTarget(name: "fake-claude", dependencies: ["NucleicCore"]),
    .executableTarget(name: "fake-grok", dependencies: ["NucleicCore"]),
    .testTarget(
        name: "NucleicCoreTests",
        dependencies: ["NucleicCore", "NucleicTailnet"],
        resources: [.copy("Fixtures")],
        // The TailscaleKit binary framework is staged at the build-products root, which
        // executables reach via their default rpath but .xctest bundles do not (their
        // rpaths point at PackageFrameworks + the bundle's own Frameworks dir). Walk the
        // three levels from Contents/MacOS/<binary> back up to the products dir.
        linkerSettings: [.unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@loader_path/../../.."])]
    ),
    .executableTarget(name: "nucleic-spike", dependencies: ["NucleicCore"]),
    // Standalone de-risking spike for the container rework: drives the real `ContainerEngine`
    // end-to-end — pulls an image from a registry, boots the VM, execs a process, and streams
    // its stdout through `ContainerizedProcessHandle` (the agent's path). Run signed with
    // signing/spike.entitlements; not shipped.
    .executableTarget(
        name: "container-spike",
        dependencies: [
            "NucleicCore",
            .product(name: "Containerization", package: "containerization"),
            .product(name: "ContainerizationOCI", package: "containerization"),
        ]),
    // Standalone de-risking spike for the macOS-VM rework: drives the real `MacVMEngine`
    // end-to-end on Apple's `Virtualization` framework — clone the golden base, boot the guest,
    // `ssh` a command in, and stream stdout (the `mac_vm_exec` agent path); `NUCLEIC_MACVM_BUILD_BASE=1`
    // runs the one-time macOS install instead. Run signed with signing/spike.entitlements; not shipped.
    .executableTarget(name: "macvm-spike", dependencies: ["NucleicCore"]),
    // The iPhone app's transcript projection (pure Foundation + NucleicProtocol model
    // folding), compiled here as a host-testable library. The iOS app target compiles these
    // same sources directly via its file-system-synchronized group; this target exists so the
    // incremental projector's prefix-equivalence suite (a required safety net —
    // docs/TRANSCRIPT_INCREMENTAL_PROJECTION.md) runs under plain `swift test`, where the
    // Xcode project has no test target. `sources` is an explicit allowlist: the folder's
    // other files are SwiftUI views this library must not build.
    .target(
        name: "NucleicRemoteProjection",
        dependencies: ["NucleicProtocol"],
        path: "ios/NucleicRemote/NucleicRemote/Views/Transcript",
        // The folder's other files are SwiftUI views compiled only by the Xcode iOS app
        // target; excluding them keeps this host-testable library building just the two
        // pure-projection sources and silences SwiftPM's "unhandled files" warning. Add
        // any new sibling view here (or it re-triggers the warning).
        exclude: [
            "AskUserQuestionResultCard.swift",
            "GitCommitCard.swift",
            "HostCommandSummary.swift",
            "HostExecCard.swift",
            "MarkdownText.swift",
            "ToolGroupRow.swift",
        ],
        sources: ["TranscriptProjection.swift", "IncrementalTranscriptProjection.swift"]),
    .testTarget(
        name: "NucleicRemoteProjectionTests",
        dependencies: ["NucleicRemoteProjection", "NucleicProtocol"]),
]

let package = Package(
    name: "Nucleic",
    // NucleicProtocol (the shared sync wire layer) must build for iOS too — that's what the
    // NucleicRemote iPhone client links. The host-only targets (NucleicCore/App/spike) use
    // macOS-only APIs and are simply never built for iOS.
    //
    // macOS floor is 26 (Tahoe): the container sandbox is built directly on Apple's
    // `containerization` framework, whose in-process vmnet networking requires macOS 26 + Apple
    // silicon. `containerization` is a dependency of NucleicCore ONLY (never of the iOS-linked
    // NucleicProtocol), so the iOS build resolves the package graph but never compiles it.
    //
    // iOS floor is 18.1: TailscaleKit ships with an 18.1 minimum (its `state()` methods use
    // the Failure-typed `any AsyncSequence` existential, an iOS 18 Swift-runtime feature), and
    // SwiftPM has no per-target floors, so the iOS-linked targets rise with it. Every device
    // that runs iOS 17 also runs 18.1, so this drops no hardware — only stale installs.
    platforms: [.macOS(.v26), .iOS("18.1")],
    products: [
        .library(name: "NucleicProtocol", targets: ["NucleicProtocol"]),
        // The Tailnet transport (embedded tsnet node + fd-backed FrameChannel). A separate
        // product because the iPhone client links it directly (NucleicCore is host-only).
        .library(name: "NucleicTailnet", targets: ["NucleicTailnet"]),
        .library(name: "NucleicCore", targets: ["NucleicCore"]),
        // The headless Antimatter runner host (docs/ANTIMATTER_RUNNER.md §9): the same
        // NucleicCore runtime as the app, no UI. Runs on a spare Mac (self-host v0) AND on
        // Linux — the runner-container daemon.
        .executable(name: "nucleicd", targets: ["nucleicd"]),
        // Headless mesh client for runner smoke tests (docs/ANTIMATTER_RUNNER.md §0.2 item 2):
        // pairs from a pairing code, dials the relay, starts a chat, answers approvals over the
        // wire. NucleicProtocol-only, so it builds everywhere — incl. the static musl target.
        .executable(name: "nucleic-smoke", targets: ["nucleic-smoke"]),
    ] + (onLinux ? [] : [
        // Product (binary / process) name varies by channel — see `appProductName`.
        .executable(name: appProductName, targets: ["NucleicApp"]),
        // Adapter-contract test stubs (fed to NucleicCoreTests). Darwin-only: they lean on
        // Foundation surfaces corelibs doesn't ship (`FileHandle.bytes`), and the core test
        // suite they feed runs on Darwin.
        .executable(name: "fake-claude", targets: ["fake-claude"]),
        .executable(name: "fake-grok", targets: ["fake-grok"]),
        .executable(name: "nucleic-spike", targets: ["nucleic-spike"]),
        .executable(name: "container-spike", targets: ["container-spike"]),
        .executable(name: "macvm-spike", targets: ["macvm-spike"]),
    ]),
    dependencies: [
        .package(url: "https://github.com/groue/GRDB.swift.git", from: "7.0.0"),
        // The Noise/CBOR crypto on Linux (docs/ANTIMATTER_RUNNER.md §9): swift-crypto is the
        // cross-platform CryptoKit — NucleicProtocol imports it only where CryptoKit is absent
        // (`#if canImport(CryptoKit)`), and the NucleicProtocolTests Noise/enrollment vectors
        // pin the two backends byte-for-byte. Already in the graph transitively (containerization
        // → grpc-swift), so this adds no new resolution.
        .package(url: "https://github.com/apple/swift-crypto.git", from: "3.0.0"),
        // The relay WebSocket on Linux (docs/ANTIMATTER_RUNNER.md §9): corelibs-foundation's
        // URLSessionWebSocketTask rides libcurl's experimental WS support, absent from distro
        // builds — so the runner's socket is SwiftNIO end to end (TLS via NIOSSL, HTTP/1.1
        // upgrade, RFC 6455 client framing). Darwin/iOS keep URLSessionWebSocketTask; these
        // products are linked into NucleicProtocol on Linux only. Both packages are already in
        // the graph transitively (containerization → grpc-swift), so this adds no resolution.
        .package(url: "https://github.com/apple/swift-nio.git", from: "2.81.0"),
        .package(url: "https://github.com/apple/swift-nio-ssl.git", from: "2.27.0"),
        .package(url: "https://github.com/migueldeicaza/SwiftTerm.git", from: "1.2.0"),
        // Apple's containerization framework — the in-process runtime the `container` CLI is built
        // on. **Vendored** (third_party/containerization) at upstream commit 6b7b42ca rather than
        // pulled from github, because we carry a small patch: `LinuxContainer.Configuration` forwards
        // `vmExtensions` into `VMConfiguration.extensions` so we can attach a memory-balloon device
        // (see third_party/containerization/PATCHES.md). The package is pre-1.0 (source stability
        // holds only within a minor version); to bump, re-vendor the new commit and re-apply the
        // patch. All framework calls are centralized in `ContainerEngine`/`MemoryBalloon`.
        .package(path: "third_party/containerization"),
        // Sparkle — in-app auto-update for the directly-distributed (non-App-Store) macOS
        // builds. macOS-only and used ONLY by the NucleicApp executable target, so the iOS
        // resolution of the package graph never compiles it. Updates are delivered as signed,
        // notarized DMGs described by a per-channel appcast (see BUILD.md "Auto-update").
        .package(url: "https://github.com/sparkle-project/Sparkle", from: "2.6.0"),
    ],
    targets: [
        // Pure, platform-agnostic: identifiers, the AgentEvent model, the sync wire
        // protocol (ClientMsg/HostMsg), CBOR framing, and the Noise SecureChannel.
        // No GRDB / Process / Network — compiles for macOS, iOS, and Linux alike
        // (CryptoKit on Darwin, swift-crypto on Linux; see the swift-crypto dependency note).
        .target(
            name: "NucleicProtocol",
            dependencies: [
                .product(name: "Crypto", package: "swift-crypto", condition: .when(platforms: [.linux])),
                // The Linux relay WebSocket (RelayTransport.swift's `#else` leg) — see the
                // swift-nio dependency note above.
                .product(name: "NIOCore", package: "swift-nio", condition: .when(platforms: [.linux])),
                .product(name: "NIOPosix", package: "swift-nio", condition: .when(platforms: [.linux])),
                .product(name: "NIOHTTP1", package: "swift-nio", condition: .when(platforms: [.linux])),
                .product(name: "NIOWebSocket", package: "swift-nio", condition: .when(platforms: [.linux])),
                .product(
                    name: "NIOFoundationCompat", package: "swift-nio",
                    condition: .when(platforms: [.linux])),
                .product(name: "NIOSSL", package: "swift-nio-ssl", condition: .when(platforms: [.linux])),
            ]),
        // The Tailnet sync transport (SYNC_PROTOCOL §3): an embedded tsnet node
        // (TailscaleKit) plus the fd-backed FrameChannel both sides speak over it. Compiles
        // for macOS (host listener) and iOS (phone dialer) alike; when the TailscaleKit
        // artifact is absent the module still builds and `TailnetSupport.isBuiltIn` is false.
        .target(
            name: "NucleicTailnet",
            dependencies: ["NucleicProtocol"] + (tailscaleKitAvailable ? ["TailscaleKit"] : [])),
        .target(
            name: "NucleicCore",
            dependencies: [
                "NucleicProtocol",
                "NucleicTailnet",
                .product(name: "GRDB", package: "GRDB.swift"),
                // In-process container runtime (host-only, macOS-conditioned: on Linux the cloud
                // container IS the sandbox — `RunSpec.container` stays nil and the Container/*
                // sources compile to empty via `#if canImport(Containerization)`). EXT4 unpacking
                // + vmnet networking are reached transitively through `Containerization`;
                // `ContainerizationOCI` provides the `User`/`Platform` types used directly by
                // `ContainerEngine`.
                .product(
                    name: "Containerization", package: "containerization",
                    condition: .when(platforms: [.macOS])),
                .product(
                    name: "ContainerizationOCI", package: "containerization",
                    condition: .when(platforms: [.macOS])),
                // For `AddressAllocator` — named in the `VZInstanceExtension.configureVZ` signature
                // our `MemoryBalloon` conforms to (it lives here, not in `Containerization`).
                .product(
                    name: "ContainerizationExtras", package: "containerization",
                    condition: .when(platforms: [.macOS])),
            ],
            // Linux compiles NucleicCore without the Apple-framework surfaces: the
            // containerization sandbox engine + macOS-VM engine (stub actors in
            // LinuxSupport.swift keep the shared signatures compiling; the pure value/spec
            // files — MacVMSpec/MacVMSurface/MacVMPackage/CommandInterceptor — stay) and the
            // Network.framework LAN transport (a runner listens relay/tailnet-first;
            // docs/ANTIMATTER_RUNNER.md §9).
            exclude: onLinux
                ? [
                    "Container/ContainerEngine.swift",
                    "Container/ContainerEngine+Rootfs.swift",
                    "Container/ContainerManager.swift",
                    "Container/ContainerizedProcessHandle.swift",
                    "Container/MemoryBalloon.swift",
                    "MacVM/MacVMAgentClient.swift",
                    "MacVM/MacVMEngine.swift",
                    "MacVM/MacVMEngine+Base.swift",
                    "MacVM/MacVMEngine+Computer.swift",
                    "MacVM/MacVMEngine+ComputerAgent.swift",
                    "MacVM/MacVMEngine+HostPaths.swift",
                    "MacVM/MacVMEngine+InstallApps.swift",
                    "MacVM/MacVMEngine+InstallPackages.swift",
                    "MacVM/MacVMEngine+LinuxBase.swift",
                    "MacVM/MacVMEngine+LinuxConfig.swift",
                    "MacVM/MacVMEngine+LinuxProvision.swift",
                    "MacVM/MacVMEngine+Provision.swift",
                    "MacVM/MacVMEngine+Provision27.swift",
                    "MacVM/MacVMEngine+Reprovision.swift",
                    "MacVM/MacVMExecChannel.swift",
                    "MacVM/MacVMManager.swift",
                    "Sync/LANTransport.swift", "Sync/LANBrowser.swift",
                    "Sync/LANAddress.swift", "Sync/MeshPathMonitor.swift",
                ]
                : [],
            // The build channel reaches the container-naming code here: `ContainerManager` appends a
            // per-channel suffix (e.g. `-beta`, `-local`) to non-release container names so a beta /
            // local-dev build's containers don't collide with a release's on the shared on-disk
            // container store (ContainerEngine.defaultStorageRoot). Same define NucleicApp's banner uses.
            swiftSettings: [.define(channelDefine)]),
        .executableTarget(name: "nucleicd", dependencies: ["NucleicCore"]),
        .executableTarget(name: "nucleic-smoke", dependencies: ["NucleicProtocol"]),
        .testTarget(
            name: "NucleicProtocolTests",
            dependencies: ["NucleicProtocol"]
        ),
    ] + (onLinux ? [] : darwinOnlyTargets)
      + (tailscaleKitAvailable
        ? [.binaryTarget(name: "TailscaleKit", path: "third_party/TailscaleKit/TailscaleKit.xcframework")]
        : [])
)
