//
//  ExternalMCPManagerConversionTests.swift
//  ConfabTests
//
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
// Copyright (C) 2026 Rune Olsen

import Testing
import Foundation
@testable import Confab

@Suite("ExternalMCPManager.convertInputSchema")
struct ExternalMCPManagerConversionTests {

    /// Regression test for a real crash: Obsidian's Local REST API plugin's MCP tool schemas
    /// include at least one property with no "type" key at all — valid JSON Schema (e.g. an
    /// enum-only or composed property) — which a `prop.type!` force-unwrap used to crash on the
    /// moment a live HTTP MCP server's tools/list response reached this code.
    @Test("A property with no type at all defaults to string instead of crashing")
    func propertyWithNoTypeDefaultsToString() {
        let prop = MCPPropertySchema(type: nil, description: "no explicit type", enum: nil, items: nil)
        let schema = MCPInputSchema(type: "object", properties: ["mode": prop], required: nil)

        let parameters = ExternalMCPManager.convertInputSchema(schema)

        #expect(parameters.properties["mode"]?.type == "string")
        #expect(parameters.properties["mode"]?.description == "no explicit type")
    }

    @Test("integer is normalized to number")
    func integerNormalizesToNumber() {
        let prop = MCPPropertySchema(type: "integer", description: nil, enum: nil, items: nil)
        let schema = MCPInputSchema(type: "object", properties: ["count": prop], required: nil)

        let parameters = ExternalMCPManager.convertInputSchema(schema)

        #expect(parameters.properties["count"]?.type == "number")
    }

    @Test("An unrecognized type string falls back to string")
    func unrecognizedTypeFallsBackToString() {
        let prop = MCPPropertySchema(type: "something-unusual", description: nil, enum: nil, items: nil)
        let schema = MCPInputSchema(type: "object", properties: ["weird": prop], required: nil)

        let parameters = ExternalMCPManager.convertInputSchema(schema)

        #expect(parameters.properties["weird"]?.type == "string")
    }

    @Test("Recognized types (string/number/boolean/array/object) pass through unchanged")
    func recognizedTypesPassThrough() {
        let types = ["string", "number", "boolean", "array", "object"]
        var properties: [String: MCPPropertySchema] = [:]
        for t in types {
            properties[t] = MCPPropertySchema(type: t, description: nil, enum: nil, items: nil)
        }
        let schema = MCPInputSchema(type: "object", properties: properties, required: nil)

        let parameters = ExternalMCPManager.convertInputSchema(schema)

        for t in types {
            #expect(parameters.properties[t]?.type == t)
        }
    }
}
