//
// LDASTools frameCPP - A library implementing the LIGO/Virgo frame
// specification
//
// Copyright (C) 2025 California Institute of Technology
//
// LDASTools frameCPP is free software; you may redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 (GPLv2) of the
// License or at your discretion, any later version.
//
// LDASTools frameCPP is distributed in the hope that it will be useful, but
// without any warranty or even the implied warranty of merchantability
// or fitness for a particular purpose. See the GNU General Public
// License (GPLv2) for more details.
//
// Neither the names of the California Institute of Technology (Caltech),
// The Massachusetts Institute of Technology (M.I.T), The Laser
// Interferometer Gravitational-Wave Observatory (LIGO), nor the names
// of its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// You should have received a copy of the licensing terms for this
// software included in the file LICENSE located in the top-level
// directory of this package. If you did not, you can view a copy at
// http://dcc.ligo.org/M1500244/LICENSE
//

#ifndef FrameCPP__UNIVERSAL__IMPL__FrHeaderClassicIO_HH
#define FrameCPP__UNIVERSAL__IMPL__FrHeaderClassicIO_HH

#include "framecpp/Universal/impl/FrHeaderData.hh"

#include "framecpp/Common/Description.hh"
#include "framecpp/Common/FrameStream.hh"
#include "framecpp/Common/TOCInfo.hh"

#include "framecpp/Universal/impl/FrameSpec.hh"

#include "ldastoolsal/types.hh"
#include "ldastoolsal/Logger.hh"

namespace FrameCPP
{
    namespace Universal
    {
        class FrHeader;

        namespace FrHeaderImpl
        {
            template < typename T >
            class ClassicIO
                : public virtual Data,
                  public Common::TOCInfo,
                  public Common::FrameSpec::Object // Note: Not
                                                   // ObjectWithChecksum
            {
            public:
                // Type definitions required by FrameSpec templates
                typedef T               self_type;
                typedef Common::IStream istream_type;
                typedef Common::OStream ostream_type;

                // Bring base class GetDescription methods into scope
                using FrameCPP::Common::FrameSpec::Object::GetDescription;

            protected:
                /// @brief Get the logger for FrHeader debugging (static
                /// version)
                /// @return Static logger instance (thread-safe, lazy
                /// initialization)
                static SimpleLogger*
                logger( )
                {
                    static SimpleLogger* instance =
                        get_channel_logger( "framecpp.frheader" );
                    return instance;
                }

            public:
                //-------------------------------------------------------
                //
                //-------------------------------------------------------
                ClassicIO( )
                    : Common::FrameSpec::Object(
                          FrameSpecId( ), nullptr, DATA_FORMAT_VERSION )
                {
                }

                ClassicIO( const ClassicIO& ) = default;
                ClassicIO( ClassicIO&& ) = default;
                ClassicIO& operator=( const ClassicIO& ) = delete;
                ClassicIO& operator=( ClassicIO&& ) = delete;

                virtual const Common::Description*
                GetDescription( unsigned int version ) const override;

                //---------------------------------------------------------------
                /// \brief equality operator
                ///
                /// \param[in] RHS
                ///     The FrHeader object to be compared.
                ///
                /// \return
                ///     The value true is returned if this object is
                ///     equivelent to the RHS instance; false otherwise.
                //---------------------------------------------------------------
                bool operator==( const FrHeader& RHS ) const;

                //-----------------------------------------------------------------
                /// \brief equality operator for abstract data type
                ///
                /// \param[in] RHS
                ///     The object to be compared.
                ///
                /// \return
                ///     The value true is returned if this object is equivelent
                ///     to the RHS instance; false otherwise.
                //-----------------------------------------------------------------
                virtual bool
                operator==( const Common::FrameSpec::Object& RHS ) const override;

            protected:
                //-----------------------------------------------------------------
                /// \brief The name structure name of this object.
                ///
                /// \return
                ///     The name of the structure as specified by the frame
                ///     specification.
                //-----------------------------------------------------------------
                virtual const char*
                ObjectStructName( ) const override
                {
                    return ( FrameSpecName( ) );
                }

                //-----------------------------------------------------------------
                /// \brief Get the frame specification name
                //-----------------------------------------------------------------
                static const char*
                FrameSpecName( )
                {
                    return "FrHeader";
                }

            private:
#if WORKING
                //-----------------------------------------------------------------
                /// \brief Get stream version helper
                /// FrHeader determines version from its own data structure
                //-----------------------------------------------------------------
                auto
                StreamVersion( const Common::StreamBase& stream ) const
                {
                    // For FrHeader, get version from the stream context, not
                    // the object Cast to FrameStream to access version_stream()
                    // method
                    const Common::FrameStream& frame_stream =
                        static_cast< const Common::FrameStream& >( stream );
                    auto version = frame_stream.version_stream( );
                    return version;
                }
#endif /* WORKING */

            public:
                // Implement pure virtual methods from
                // FrameSpec::ObjectInterface

                //-----------------------------------------------------------------
                /// \brief Number of bytes needed to write this structure
                /// Future-proof calculation based on FrHeaderData structure
                //-----------------------------------------------------------------
                virtual FrameCPP::streamsize_type
                Bytes( const FrameCPP::stream_base_type& Stream ) const override
                {
                    auto frame_stream_version = StreamVersion( Stream );

                    // Base size: bytes 0-37 (Common::FrHeader + fixed frame
                    // fields)
                    cmn_streamsize_type size =
                        Common::FrHeader::Bytes( ) + // bytes 0-6
                        sizeof( SizeOf_INT_2_type ) + // byte 7
                        sizeof( SizeOf_INT_4_type ) + // byte 8
                        sizeof( SizeOf_INT_8_type ) + // byte 9
                        sizeof( SizeOf_REAL_4_type ) + // byte 10
                        sizeof( SizeOf_REAL_8_type ) + // byte 11
                        sizeof( Endian_2_byte_type ) + // bytes 12-13
                        sizeof( Endian_4_byte_type ) + // bytes 14-17
                        sizeof( Endian_8_byte_type ) + // bytes 18-25
                        sizeof( PI_SINGLE_type ) + // bytes 26-29
                        sizeof( PI_DOUBLE_type ); // bytes 30-37

                    // Version-specific bytes 38-39
                    if ( frame_stream_version >= 8 )
                    {
                        // v8+: frameLibrary + checksumScheme
                        size += sizeof( frameLibrary_type ) + // byte 38
                            sizeof( checksumScheme_type ); // byte 39
                    }
                    else
                    {
                        // v3-v7: legacy 'A''Z' marker
                        size += sizeof(
                            typename v3::legacy_marker_type ); // bytes 38-39
                    }

                    return size;
                }

                //-----------------------------------------------------------------
                /// \brief Virtual constructor - Create object from stream
                //-----------------------------------------------------------------
                virtual Common::FrameSpec::Object*
                Create( FrameCPP::istream_type& Stream ) const override
                {

                    T* obj = new T( );

                    // Get version from the stream context, not from the
                    // uninitialized object Cast to FrameStream to access
                    // version_stream() method
#if WORKING
                    const Common::FrameStream& frame_stream =
                        static_cast< const Common::FrameStream& >( Stream );
#endif /* WORKING */
                    auto frame_stream_version = StreamVersion( Stream );

                    // Log entry point and stream position
                    logger_log_debug(
                        logger( ),
                        45,
                        "FrHeaderClassicIO::Create() entry - stream_version: ",
                        frame_stream_version,
                        ", position: ",
                        Stream.tellg( ) );

                    // IMPORTANT: The Common::FrHeader portion (bytes 0-6) has
                    // already been read by loadFrHeader() when it called
                    // Common::FrHeader constructor. We only need to read the
                    // remaining bytes 7-39.

                    // Bytes 7-37: Frame-specific fields with correct names
                    Stream >> obj->SizeOf_INT_2;

                    Stream >> obj->SizeOf_INT_4;

                    Stream >> obj->SizeOf_INT_8;

                    Stream >> obj->SizeOf_REAL_4;

                    Stream >> obj->SizeOf_REAL_8;

                    Stream >> obj->Endian_2_byte;

                    Stream >> obj->Endian_4_byte;

                    Stream >> obj->Endian_8_byte;

                    Stream >> obj->PI_SINGLE;

                    Stream >> obj->PI_DOUBLE;

                    // Log the critical header fields that help detect byte
                    // swapping
                    logger_log_debug(
                        logger( ),
                        45,
                        "FrHeaderClassicIO::Create() read header fields - ",
                        "SizeOf_INT_2: ",
                        obj->SizeOf_INT_2,
                        ", SizeOf_INT_4: ",
                        obj->SizeOf_INT_4,
                        ", Endian_4_byte: ",
                        obj->Endian_4_byte,
                        ", Endian_8_byte: ",
                        obj->Endian_8_byte,
                        ", PI_SINGLE: ",
                        obj->PI_SINGLE,
                        ", PI_DOUBLE: ",
                        obj->PI_DOUBLE,
                        ", position: ",
                        Stream.tellg( ) );

                    // Bytes 38-39: Version-specific handling
                    if ( frame_stream_version >= 8 )
                    {
                        // v8+ uses frameLibrary and checksumScheme
                        Stream >> obj->m_frameLibrary >> obj->m_checksumScheme;

                        // Validate checksumScheme - only NONE (0) and CRC (1) are valid
                        // If invalid, default to CRC for v8+
                        if ( obj->m_checksumScheme != Common::CheckSum::NONE &&
                             obj->m_checksumScheme != Common::CheckSum::CRC )
                        {
                            obj->m_checksumScheme = static_cast<checksumScheme_type>(Common::CheckSum::CRC);
                        }

                        // CRITICAL: Set up the stream's file checksum filter based on the checksumScheme
                        // This must be done AFTER reading the FrHeader to ensure proper checksum validation
                        Stream.SetCheckSumFile( static_cast<Common::CheckSum::kind_type>(obj->m_checksumScheme) );
                    }
                    else
                    {
                        // v3-v7 uses legacy 'A''Z' constant
                        CHAR legacyMarker[ 2 ];
                        Stream >> legacyMarker[ 0 ] >> legacyMarker[ 1 ];
                        // Set default values for v8+ fields
                        obj->m_frameLibrary =
                            Common::FrHeader::FRAME_LIBRARY_FRAMECPP;
                        obj->m_checksumScheme = 0;
                    }

                    // NOTE: Common::FrHeader fields (originator, version, etc.)
                    // should be initialized by the FrHeader constructor or by
                    // the calling code. Create() focuses only on reading the
                    // frame-specific data from the stream.

                    // Detect byte order and set m_reorder_bytes and
                    // m_byte_order
                    obj->detectAndSetByteOrder( );

                    return obj;
                }

                //-----------------------------------------------------------------
                /// \brief Write the structure to the stream
                //-----------------------------------------------------------------
                virtual void
                Write( FrameCPP::ostream_type& Stream ) const override
                {
                    auto frame_stream_version = StreamVersion( Stream );

                    // For v8+, set up FrHeader checksum filter
                    if ( frame_stream_version >= 8 )
                    {
                        // Validate and auto-detect checksumScheme
                        // CRITICAL: Must handle uninitialized values (garbage)
                        bool needsAutoDetect = false;

                        // Check if m_checksumScheme is valid (NONE or CRC) or uninitialized
                        if ( m_checksumScheme != Common::CheckSum::NONE && m_checksumScheme != Common::CheckSum::CRC )
                        {
                            // Invalid or uninitialized - needs auto-detection
                            needsAutoDetect = true;
                        }
                        else if ( m_checksumScheme == 0 )
                        {
                            // Explicitly set to NONE - also auto-detect from stream
                            needsAutoDetect = true;
                        }

                        if ( needsAutoDetect )
                        {
                            auto* fileChecksumFilter = Stream.GetCheckSumFile();
                            if ( fileChecksumFilter )
                            {
                                // Get the checksum type and validate it
                                Common::CheckSum::kind_type filterType = fileChecksumFilter->Type();

                                // Only use the filter type if it's valid (NONE or CRC)
                                // If invalid, default to CRC for v8+
                                if ( filterType == Common::CheckSum::NONE || filterType == Common::CheckSum::CRC )
                                {
                                    const_cast<ClassicIO*>(this)->m_checksumScheme =
                                        static_cast<checksumScheme_type>( filterType );
                                }
                                else
                                {
                                    // Invalid checksum type - default to CRC for v8+
                                    const_cast<ClassicIO*>(this)->m_checksumScheme =
                                        static_cast<checksumScheme_type>( Common::CheckSum::CRC );
                                }
                            }
                            else
                            {
                                // No file checksum filter - default to NONE
                                const_cast<ClassicIO*>(this)->m_checksumScheme =
                                    static_cast<checksumScheme_type>( Common::CheckSum::NONE );
                            }
                        }

                        // Enable FrHeader checksum filter if checksum scheme is not NONE
                        if ( m_checksumScheme != 0 )
                        {
                            Stream.SetCheckSumFrHeader( static_cast<Common::CheckSum::kind_type>( m_checksumScheme ) );
                        }
                    }

                    // Write the FrHeader bytes (will flow through the checksum filter)
                    // CRITICAL: Write the Common::FrHeader portion first (bytes 0-6)
                    Common::FrHeader::Write( Stream );

                    // Write frame-specific fields (bytes 7-37)
                    Stream << SizeOf_INT_2 << SizeOf_INT_4 << SizeOf_INT_8
                           << SizeOf_REAL_4 << SizeOf_REAL_8 << Endian_2_byte
                           << Endian_4_byte << Endian_8_byte << PI_SINGLE
                           << PI_DOUBLE;

                    // Bytes 38-39: Version-specific handling
                    if ( frame_stream_version >= 8 )
                    {
                        // CRITICAL: Validate checksumScheme one final time before writing
                        // This catches cases where an invalid value was set somewhere else
                        checksumScheme_type validated_scheme = m_checksumScheme;

                        logger_log_debug(logger(), 10,
                            "FrHeaderClassicIO::Write() BEFORE validation - m_checksumScheme: ",
                            static_cast<int>(m_checksumScheme));

                        if ( validated_scheme != Common::CheckSum::NONE &&
                             validated_scheme != Common::CheckSum::CRC )
                        {
                            logger_log_debug(logger(), 10,
                                "FrHeaderClassicIO::Write() INVALID checksumScheme detected: ",
                                static_cast<int>(validated_scheme), " - defaulting to CRC");
                            // Invalid checksum scheme - default to CRC for v8+
                            validated_scheme = static_cast<checksumScheme_type>( Common::CheckSum::CRC );
                        }

                        logger_log_debug(logger(), 10,
                            "FrHeaderClassicIO::Write() AFTER validation - validated_scheme: ",
                            static_cast<int>(validated_scheme), ", m_frameLibrary: ",
                            static_cast<int>(m_frameLibrary));

                        Stream << m_frameLibrary << validated_scheme;

                        // Capture and store the FrHeader checksum value
                        if ( validated_scheme != 0 )
                        {
                            // Flush the stream to ensure bytes flow through the filter
                            Stream.flush();

                            auto* filter = Stream.GetCheckSumFrHeader();
                            if ( filter )
                            {
                                Stream.SetFrHeaderChecksumValue( filter->Value() );
                            }
                            // Remove the filter now that we've captured the value
                            Stream.SetCheckSumFrHeader( Common::CheckSum::NONE );
                        }
                    }
                    else
                    {
                        // v3-v7 uses legacy 'A''Z' constant
                        Stream << static_cast< CHAR >( 'A' )
                               << static_cast< CHAR >( 'Z' );
                    }
                }

                //
                // NOTE: demote() and promote() override methods removed.
                // Universal objects are version-agnostic - all version adaptation
                // happens at the I/O layer via pCreate/pWrite/pRead.
                //

            protected:
            private:
                //-----------------------------------------------------------------
                //-----------------------------------------------------------------
                typedef Common::FrameSpec::Object object_type;

                using Common::FrameSpec::Object::Create;

#if WORKING_VIRTUAL_TOCQUERY
            public:
                //-----------------------------------------------------------------
                /// \brief Answer requests for information as needed by TOC
                ///
                /// \param[in] InfoClass
                ///     Class of information being requested.
                //-----------------------------------------------------------------
                void TOCQuery( int InfoClass, ... ) const;
#else /* WORKING_VIRTUAL_TOCQUERY */
            protected:
                //-----------------------------------------------------------------
                /// \brief Answer requests for information as needed by TOC
                ///
                /// \param[in] InfoClass
                ///     Class of information being requested.
                /// \param[in] vl
                ///     Variable argument list of requested data.
                //-----------------------------------------------------------------
                virtual void vTOCQuery( int InfoClass, va_list vl ) const override;
#endif /* ! WORKING_VIRTUAL_TOCQUERY */
            };

            template < typename T >
            void
            ClassicIO< T >::
#if WORKING_VIRTUAL_TOCQUERY
                TOCQuery( int InfoClass, ... ) const
#else /*  WORKING_VIRTUAL_TOCQUERY */
                vTOCQuery( int InfoClass, va_list vl ) const
#endif /*  WORKING_VIRTUAL_TOCQUERY */
            {
                using Common::TOCInfo;

#if WORKING_VIRTUAL_TOCQUERY
                va_list vl;
                va_start( vl, InfoClass );
#endif /*  WORKING_VIRTUAL_TOCQUERY */

#if WORKING_VIRTUAL_TOCQUERY
                va_end( vl )
#endif /*  WORKING_VIRTUAL_TOCQUERY */
                    ;
            } // TOCQuery
        } // namespace FrHeaderImpl
    } // namespace Universal
} // namespace FrameCPP

#endif /* FrameCPP__UNIVERSAL__IMPL__FrHeaderClassicIO_HH */
