using System;
using System.Diagnostics.CodeAnalysis;

namespace OpenAI.Assistants;

[Experimental("OPENAI001")]
public class TextAnnotationUpdate
{
    /// <summary>
    /// The index of the content item that this annotation applies to.
    /// </summary>
    public int ContentIndex
        => _fileSearchCitation?.Index
        ?? _codeCitation?.Index
        ?? (_internalAnnotation?.SerializedAdditionalRawData.TryGetValue("index", out BinaryData indexData) == true
            ? int.Parse(indexData.ToString())
            : -1);

    /// <summary>
    /// The index in the message content at which the citation begins.
    /// </summary>
    public int? StartIndex
        => _fileSearchCitation?.StartIndex
        ?? _codeCitation?.StartIndex
        ?? (_internalAnnotation?.SerializedAdditionalRawData.TryGetValue("start_index", out BinaryData indexData) == true
            ? int.Parse(indexData.ToString())
            : null);

    /// <summary>
    /// The index in the message content at which the citation ends.
    /// </summary>
    public int? EndIndex
        => _fileSearchCitation?.EndIndex
        ?? _codeCitation?.EndIndex
        ?? (_internalAnnotation?.SerializedAdditionalRawData.TryGetValue("start_index", out BinaryData indexData) == true
            ? int.Parse(indexData.ToString())
            : null);

    /// <summary>
    /// The text in the message content that should be replaced.
    /// </summary>
    public string TextToReplace
        => _fileSearchCitation?.Text
        ?? _codeCitation?.Text
        ?? (_internalAnnotation?.SerializedAdditionalRawData.TryGetValue("text", out BinaryData textData) == true
            ? textData.ToString()
            : null);

    /// <summary>
    /// The ID of the file cited by the <c>file_search</c> tool for this annotation.
    /// </summary>
    public string InputFileId => _fileSearchCitation?.FileCitation?.FileId;

    /// <summary>
    /// The ID of the file that was generated by the <c>code_interpreter</c> tool for this citation.
    /// </summary>
    public string OutputFileId => _codeCitation?.FilePath?.FileId;

    internal readonly InternalMessageDeltaTextContentAnnotation _internalAnnotation;
    private readonly InternalMessageDeltaContentTextAnnotationsFileCitationObject _fileSearchCitation;
    private readonly InternalMessageDeltaContentTextAnnotationsFilePathObject _codeCitation;

    internal TextAnnotationUpdate(InternalMessageDeltaTextContentAnnotation internalAnnotation)
    {
        _internalAnnotation = internalAnnotation;
        _fileSearchCitation = internalAnnotation as InternalMessageDeltaContentTextAnnotationsFileCitationObject;
        _codeCitation = internalAnnotation as InternalMessageDeltaContentTextAnnotationsFilePathObject;
    }
}