// Copyright (C) 2026 Kiyotsugu Arai
// SPDX-License-Identifier: LGPL-3.0-or-later

// Rational.hpp
// 多倍長有理数ライブラリのメインヘッダーファイル

#ifndef CALX_RATIONAL_HPP
#define CALX_RATIONAL_HPP

#include <math/core/mp/Int.hpp>
#include <math/core/mp/Rational/RationalBase.hpp>
#include <math/core/mp/Rational/RationalTraits.hpp>
#include <math/core/mp/Rational/RationalConstants.hpp>

// --- std::formatter 特殊化 ---
#include <format>

template<>
struct std::formatter<calx::Rational> {
    int precision_ = -1;
    char type_ = 0;  // 0=default(num/den), 'f'=decimal

    constexpr auto parse(std::format_parse_context& ctx) {
        auto it = ctx.begin();
        auto end = ctx.end();
        if (it != end && *it == '.') {
            ++it;
            precision_ = 0;
            while (it != end && *it >= '0' && *it <= '9') {
                precision_ = precision_ * 10 + (*it - '0');
                ++it;
            }
        }
        if (it != end && *it != '}') {
            if (*it == 'f') {
                type_ = 'f';
                ++it;
            } else {
                throw std::format_error("invalid format spec for Rational");
            }
        }
        return it;
    }

    auto format(const calx::Rational& val, std::format_context& ctx) const {
        std::string result;
        if (type_ == 'f') {
            result = val.toDecimal(precision_ >= 0 ? precision_ : 20);
        } else {
            result = val.toString();
        }
        return std::format_to(ctx.out(), "{}", result);
    }
};

#endif // CALX_RATIONAL_HPP
