import Foundation
import UIKit
import DGis

/// Container bridge: SDK initialization and map view factory.
/// One shared instance; creates one DGisMapViewBridge per map (supports multiple maps per app).
@objcMembers
public final class DGisBridge: NSObject {

    public static let shared = DGisBridge()

    private var sdk: DGis.Container?

    // MARK: - SDK initialization

    public func initialize(keyPath: String) -> Bool {
        do {
            let key = KeySource.fromAsset(KeyFromAsset(path: keyPath))
            sdk = DGis.Container(keySource: key)
            return true
        } catch {
            NSLog("DGisBridge: failed to create container: \(error)")
            return false
        }
    }

    public func isInitialized() -> Bool {
        sdk != nil
    }

    // MARK: - Map view creation

    /// Creates a new map view bridge. Each call returns a separate instance (multiple maps supported).
    @MainActor
    public func createMapView(centerLat: Double, centerLng: Double, zoom: Double) -> DGisMapViewBridge? {
        guard let sdk = sdk else { return nil }
        var options = DGis.MapOptions.default
        options.devicePPI = DGis.DevicePpi.autodetected
        options.position = DGis.CameraPosition(
            point: DGis.GeoPoint(
                latitude: DGis.Latitude(value: centerLat),
                longitude: DGis.Longitude(value: centerLng)
            ),
            zoom: DGis.Zoom(value: Float(zoom))
        )
        do {
            let factory = try sdk.makeMapFactory(options: options)
            let map = factory.map
            let mapObjectManager = DGis.MapObjectManager(map: map)
            return DGisMapViewBridge(
                sdk: sdk,
                factory: factory,
                map: map,
                mapObjectManager: mapObjectManager
            )
        } catch {
            NSLog("DGisBridge: makeMapFactory failed: \(error)")
            return nil
        }
    }

    // MARK: - Image factory (for Obj-C that loads icon async)

    public func makeImage(from image: UIImage) -> Any? {
        guard let container = sdk else { return nil }
        return try? container.imageFactory.make(image: image)
    }
}
