import Foundation

// The `os.Logger` stand-in for every platform without the `os` module — Linux runners AND the
// Windows host (docs/WINDOWS_PORT.md §4.3) — lifted out of LinuxSupport.swift so both share
// one file. `#if`-gated to compile ONLY where the Apple original is absent, so Darwin builds
// are untouched.

#if !canImport(os)
/// The narrow slice of `os.Logger` NucleicCore uses (module-level loggers + privacy-annotated
/// interpolation), emitted to stderr with the subsystem/category label. Structured logging can
/// replace this with swift-log later (rolling files at `%LOCALAPPDATA%\Nucleic\logs` on
/// Windows); the call sites won't change.
public struct Logger: Sendable {
    public struct Message: ExpressibleByStringInterpolation, Sendable {
        public struct Privacy: Sendable {
            public static let `public` = Privacy()
            public static let `private` = Privacy()
            public static let auto = Privacy()
            public static let sensitive = Privacy()
        }

        public struct StringInterpolation: StringInterpolationProtocol, Sendable {
            var rendered = ""
            public init(literalCapacity: Int, interpolationCount: Int) {
                rendered.reserveCapacity(literalCapacity + interpolationCount * 8)
            }
            public mutating func appendLiteral(_ literal: String) { rendered += literal }
            public mutating func appendInterpolation<T>(_ value: @autoclosure () -> T) {
                rendered += String(describing: value())
            }
            public mutating func appendInterpolation<T>(
                _ value: @autoclosure () -> T, privacy: Privacy
            ) {
                rendered += String(describing: value())
            }
        }

        let rendered: String
        public init(stringLiteral value: String) { rendered = value }
        public init(stringInterpolation: StringInterpolation) {
            rendered = stringInterpolation.rendered
        }
    }

    let label: String
    public init(subsystem: String, category: String) { label = "\(subsystem).\(category)" }

    public func trace(_ message: Message) { emit("trace", message) }
    public func debug(_ message: Message) { emit("debug", message) }
    public func info(_ message: Message) { emit("info", message) }
    public func notice(_ message: Message) { emit("notice", message) }
    public func warning(_ message: Message) { emit("warning", message) }
    public func error(_ message: Message) { emit("error", message) }
    public func fault(_ message: Message) { emit("fault", message) }

    private func emit(_ level: String, _ message: Message) {
        FileHandle.standardError.write(Data("[\(label)] \(level): \(message.rendered)\n".utf8))
    }
}
#endif
