/*
 Copyright (C) 2024 Luigi Ballabio

 This file is released under the terms of the 3-Clause BSD License
 (see https://opensource.org/license/bsd-3-clause/)

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <ql/instruments/bond.hpp>
#include <ql/instruments/bonds/fixedratebond.hpp>
#include <ql/instruments/bonds/amortizingfixedratebond.hpp>
#include <ql/cashflows/fixedratecoupon.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/daycounters/thirty360.hpp>
#include <ql/time/schedule.hpp>
#include <ql/settings.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <iostream>
#include <iomanip>

using namespace QuantLib;

void display(const Leg& cashflows) {
   std::cout << std::setw(10) << "date";
   std::cout << std::setw(12) << "nominal";
   std::cout << std::setw(10) << "rate";
   std::cout << std::setw(12) << "amount";
   std::cout << std::endl;

   std::cout << std::fixed << std::setprecision(2);

   for (auto c : cashflows) {
      std::cout << io::iso_date(c->date());
      auto coupon = ext::dynamic_pointer_cast<Coupon>(c);
      if (coupon) {
         std::cout << std::setw(12) << coupon->nominal();
         std::cout << std::setw(10) << coupon->rate();
      } else {
         std::cout << std::setw(12) << "n/a";
         std::cout << std::setw(10) << "n/a";
      }
      std::cout << std::setw(12) << c->amount();
      std::cout << std::endl;
   }
   std::cout << std::endl;
};

int main() {

   Settings::instance().evaluationDate() =
       Date(15, January, 2024);

   // A simple fixed-rate bond

   Schedule schedule =
       MakeSchedule()
       .from(Date(8, February, 2021))
       .to(Date(8, February, 2026))
       .withFrequency(Semiannual)
       .withCalendar(TARGET())
       .withConvention(Following)
       .backwards();

   int settlementDays = 3;
   auto issueDate =
       Date(5, February, 2021);
   auto dayCount =
       Thirty360(Thirty360::BondBasis);

   Leg fixedCoupons =
      FixedRateLeg(schedule)
       .withCouponRates(0.03, dayCount)
       .withNotionals(10000.0);

   auto bond1 =
       Bond(settlementDays,
            TARGET(),
            issueDate,
            fixedCoupons);

   display(bond1.cashflows());

   Rate y = bond1.yield(98.0, dayCount,
                        Compounded, Semiannual);

   std::cout << std::setprecision(4)
             << io::rate(y)
             << std::endl << std::endl;

   // A shortcut to the same bond

   auto bond1b =
       FixedRateBond(
          settlementDays,
          10000.0,
          schedule,
          {0.03},
          dayCount);

   display(bond1b.cashflows());

   // An amortizing fixed-rate bond

   Leg amortizingCoupons =
      FixedRateLeg(schedule)
       .withCouponRates(0.03, dayCount)
       .withNotionals({
           10000.0, 10000.0,
           8000.0, 8000.0,
           6000.0, 6000.0,
           4000.0, 4000.0,
           2000.0, 2000.0
       });
   
   auto bond2 =
       Bond(settlementDays,
            TARGET(),
            issueDate,
            amortizingCoupons);

   display(bond2.cashflows());

   // A tricky case: a payment-in-kind bond

   Leg pikCoupons(schedule.size()-1);

   pikCoupons[0] =
      ext::make_shared<FixedRateCoupon>(
         schedule[1],
         10000.0,
         0.03,
         dayCount,
         schedule[0],
         schedule[1]);

   for (Size i=1; i<pikCoupons.size(); ++i) {
      auto previous =
          ext::dynamic_pointer_cast<Coupon>(
             pikCoupons[i-1]);
      pikCoupons[i] =
         ext::make_shared<FixedRateCoupon>(
            schedule[i+1],
            previous->nominal() + previous->amount(),
            0.03,
            dayCount,
            schedule[i],
            schedule[i+1]);
   }

   auto bond3 =
       Bond(settlementDays,
            TARGET(),
            issueDate,
            pikCoupons);

   display(bond3.cashflows());

}
