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

import Testing
import Foundation
import CoreGraphics
import AppKit
@testable import Confab

@Suite("MCPService PDF text extraction")
struct MCPServicePDFTests {

    /// Builds a real, well-formed single-page PDF (via CoreGraphics) containing the given text,
    /// writes it to a temp file, and returns the path. Using CoreGraphics rather than hand-rolled
    /// PDF bytes avoids flakiness from malformed xref tables etc.
    private func makeTestPDF(text: String) throws -> String {
        let path = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
            .appendingPathExtension("pdf")

        let pdfData = NSMutableData()
        let consumer = CGDataConsumer(data: pdfData as CFMutableData)!
        var mediaBox = CGRect(x: 0, y: 0, width: 200, height: 200)
        let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!

        context.beginPDFPage(nil)
        let attributedString = NSAttributedString(string: text, attributes: [.font: NSFont.systemFont(ofSize: 24)])
        let line = CTLineCreateWithAttributedString(attributedString)
        context.textPosition = CGPoint(x: 10, y: 100)
        CTLineDraw(line, context)
        context.endPDFPage()
        context.closePDF()

        try (pdfData as Data).write(to: path)
        return path.path
    }

    @Test("Extracts text from a real PDF's text layer")
    func extractsTextFromRealPDF() throws {
        let path = try makeTestPDF(text: "Hello World")
        defer { try? FileManager.default.removeItem(atPath: path) }

        let extracted = MCPService.shared.extractPDFText(atPath: path)
        #expect(extracted?.contains("Hello World") == true)
    }

    @Test("Returns nil for a nonexistent path")
    func returnsNilForMissingFile() {
        let extracted = MCPService.shared.extractPDFText(atPath: "/tmp/definitely-does-not-exist-\(UUID().uuidString).pdf")
        #expect(extracted == nil)
    }

    @Test("Returns nil for a file that isn't a valid PDF")
    func returnsNilForGarbageBytes() throws {
        let path = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
            .appendingPathExtension("pdf")
        try Data("not a real pdf".utf8).write(to: path)
        defer { try? FileManager.default.removeItem(at: path) }

        let extracted = MCPService.shared.extractPDFText(atPath: path.path)
        #expect(extracted == nil)
    }
}
