//===----------------------------------------------------------------------===//
// Copyright © 2026 Apple Inc. and the container project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import ContainerizationError
import ContainerizationExtras
import Foundation

public struct NetworkPluginInfo: Codable, Sendable, Hashable {
    public let plugin: String
    public let variant: String?

    public init(plugin: String, variant: String? = nil) {
        self.plugin = plugin
        self.variant = variant
    }
}

/// Configuration parameters for network creation.
public struct NetworkConfiguration: Codable, Sendable, Identifiable {
    /// A unique identifier for the network
    public let id: String

    /// The network type
    public let mode: NetworkMode

    /// When the network was created.
    public let creationDate: Date

    /// The preferred CIDR address for the IPv4 subnet, if specified
    public let ipv4Subnet: CIDRv4?

    /// The preferred CIDR address for the IPv6 subnet, if specified
    public let ipv6Subnet: CIDRv6?

    /// Key-value labels for the network.
    /// Resource labels should not be mutated, except while building a network configurations.
    public let labels: ResourceLabels

    /// Details about the network plugin that manages this network.
    /// FIXME: This field only needs to be optional while we wait for the field
    /// to be proliferated to most users when they update container.
    public let pluginInfo: NetworkPluginInfo?

    /// Creates a network configuration
    public init(
        id: String,
        mode: NetworkMode,
        ipv4Subnet: CIDRv4? = nil,
        ipv6Subnet: CIDRv6? = nil,
        labels: ResourceLabels = .init(),
        pluginInfo: NetworkPluginInfo?
    ) throws {
        self.id = id
        self.creationDate = Date()
        self.mode = mode
        self.ipv4Subnet = ipv4Subnet
        self.ipv6Subnet = ipv6Subnet
        self.labels = labels
        self.pluginInfo = pluginInfo
        try validate()
    }

    enum CodingKeys: String, CodingKey {
        case id
        case creationDate
        case mode
        case ipv4Subnet
        case ipv6Subnet
        case labels
        case pluginInfo
        // TODO: retain for deserialization compatibility for now, remove later
        case subnet
    }

    /// Create a configuration from the supplied Decoder, initializing missing
    /// values where possible to reasonable defaults.
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        id = try container.decode(String.self, forKey: .id)
        creationDate = try container.decodeIfPresent(Date.self, forKey: .creationDate) ?? Date(timeIntervalSince1970: 0)
        mode = try container.decode(NetworkMode.self, forKey: .mode)
        let subnetText =
            try container.decodeIfPresent(String.self, forKey: .ipv4Subnet)
            ?? container.decodeIfPresent(String.self, forKey: .subnet)
        ipv4Subnet = try subnetText.map { try CIDRv4($0) }
        ipv6Subnet = try container.decodeIfPresent(String.self, forKey: .ipv6Subnet)
            .map { try CIDRv6($0) }
        let decodedLabels = try container.decodeIfPresent([String: String].self, forKey: .labels) ?? [:]
        labels = try .init(decodedLabels)
        pluginInfo = try container.decodeIfPresent(NetworkPluginInfo.self, forKey: .pluginInfo)
        try validate()
    }

    /// Encode the configuration to the supplied Encoder.
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(id, forKey: .id)
        try container.encode(creationDate, forKey: .creationDate)
        try container.encode(mode, forKey: .mode)
        try container.encodeIfPresent(ipv4Subnet, forKey: .ipv4Subnet)
        try container.encodeIfPresent(ipv6Subnet, forKey: .ipv6Subnet)
        try container.encode(labels, forKey: .labels)
        try container.encodeIfPresent(pluginInfo, forKey: .pluginInfo)
    }

    private func validate() throws {
        guard id.isValidNetworkID() else {
            throw ContainerizationError(.invalidArgument, message: "invalid network ID: \(id)")
        }
    }
}

extension String {
    /// Ensure that the network ID has the correct syntax.
    fileprivate func isValidNetworkID() -> Bool {
        let pattern = #"^[a-z0-9](?:[a-z0-9._-]{0,61}[a-z0-9])?$"#
        return self.range(of: pattern, options: .regularExpression) != nil
    }
}
