#!/user/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2024 Galaxy Technologies
Licensed under the Apache License, Version 2.0
"""
import datetime
from contextlib import suppress
import numpy as np
from pricelib.common.utilities.enums import CallPut, TouchType, ExerciseType, PaymentType, EngineType, StatusType
from pricelib.common.date_handler import CN_CALENDAR, AnnualDays, global_evaluation_date
from pricelib.common.utilities.patterns import Observer, global_auto_update_status
from pricelib.common.utilities.utility import time_this, logging
from pricelib.common.product_base.option_base import OptionBase
from pricelib.pricing_engines.analytic_engines import AnalyticCashOrNothingEngine
from pricelib.pricing_engines.mc_engines import MCDigitalEngine
from pricelib.pricing_engines.fdm_engines import FdmDigitalEngine
from pricelib.pricing_engines.integral_engines import QuadDigitalEngine
from pricelib.pricing_engines.tree_engines import BiTreeDigitalEngine


class DigitalOption(OptionBase, Observer):
    """单边二元(数字)期权-现金或无(cash or nothing)
    包括欧式二元(现金或无)、美式二元(立即支付)、一触即付(到期支付)，支持M. Broadie, P. Glasserman, S.G. Kou(1999)离散观察调整"""
    touch_type = TouchType.Touch  # 触碰类型：触碰

    def __init__(self, strike, rebate, callput=CallPut.Call, exercise_type=ExerciseType.European, rebate_annual=False,
                 payment_type=PaymentType.Expire, *, maturity=None, start_date=None, end_date=None, engine=None,
                 status=StatusType.NoTouch, discrete_obs_interval=None, trade_calendar=CN_CALENDAR,
                 annual_days=AnnualDays.N365, t_step_per_year=243, stoch_process=None, s0=None, s=None, r=None, q=None,
                 vol=None, engine_method=None):
        """构造函数
        产品参数:
            strike:  float, 执行价
            rebate:  float, 行权收益, 绝对数值（非年化）
            rebate_annual: bool, 现金返还是否为年化，默认为False，即绝对数值，非年化，非百分比；若为True，则为百分比年化收益率
            callput: 看涨看跌类型，CallPut枚举类，Call/Put
            exercise_type: 行权方式，ExerciseType枚举类，European/American
            payment_type: 支付方式，PaymentType枚举类，立即支付Hit/到期支付Expire
            status: 触碰障碍的状态，StatusType枚举类，默认为NoTouch未触碰，UpTouch为向上触碰，DownTouch为向下触碰
        时间参数: 要么输入年化期限，要么输入起始日和到期日
            maturity: float，年化期限
            start_date: datetime.date，起始日
            end_date: datetime.date，到期日
            trade_calendar: 交易日历，Calendar类，默认为中国内地交易日历
            annual_days: int，每年的自然日数量
            t_step_per_year: int，每年的交易日数量
            discrete_obs_interval: 观察时间间隔. 若为连续观察，None；若为均匀离散观察，为年化的观察时间间隔
        可选参数:
            s0: float，标的期初价格，只有当 rebate_annual = True，即现金返还为年化收益率时；
               需要输入标的期初价格，将百分比的收益率转化成绝对数值
            engine: 定价引擎，PricingEngine类，以下几种引擎均支持欧式二元(现金或无)、美式二元(立即支付)、一触即付(到期支付)，
                            解析解和PDE引擎支持离散观察/连续观察，其余引擎只支持离散观察(默认为每日观察)
                    解析解: AnalyticCashOrNothingEngine
                    蒙特卡洛: MCDigitalEngine  todo 支持年化现金收益 rebate_annual
                    PDE: FdmDigitalEngine  todo 支持年化现金收益 rebate_annual
                    积分法: QuadDigitalEngine  todo 支持年化现金收益 rebate_annual
                    二叉树: BiTreeDigitalEngine  todo 支持年化现金收益 rebate_annual
            engine_method: str, 定价引擎种类。若未输入engine，可以用engine_method快捷生成指定定价引擎。可选Analytic、MC/MonteCarlo、PDE/FDM、QUAD、TREE。
            若未提供引擎engine、也未指定引擎种类engine_method的情况下，如果提供了 随机过程 或 标的价格、无风险利率、分红/融券率、波动率，
            则默认使用 二元(数字)期权-现金或无(cash or nothing)-闭式解定价引擎 Reiner and Rubinstein(1991b)
            stoch_process: 随机过程StochProcessBase对象
            s: float，标的价格
            r: float，无风险利率
            q: float，分红/融券率
            vol: float，波动率
        """
        super().__init__()
        self.trade_calendar = trade_calendar
        self.annual_days = annual_days
        self.t_step_per_year = t_step_per_year
        assert maturity is not None or (start_date is not None and end_date is not None), "Error: 到期时间或起止时间必须输入一个"
        self.start_date = start_date if start_date is not None else global_evaluation_date()  # 起始时间
        self.end_date = end_date if end_date is not None else (
                self.start_date + datetime.timedelta(days=round(maturity * annual_days.value)))  # 结束时间
        if self.trade_calendar.isholiday(self.end_date):  # 如果到期日不是交易日，向后顺延一个交易日
            self.end_date = self.trade_calendar.advance(self.end_date, datetime.timedelta(days=1))
        self.maturity = maturity if maturity is not None else (self.end_date - self.start_date).days / annual_days.value
        self.strike = strike
        self.rebate = rebate  # 行权收益，绝对值/百分比年化
        self.rebate_annual = rebate_annual  # 现金返还是否为年化
        self.callput = callput
        self.exercise_type = exercise_type
        self.payment_type = payment_type
        if self.exercise_type == ExerciseType.European or self.touch_type == TouchType.NoTouch:
            assert payment_type == PaymentType.Expire, "ValueError: 欧式二元期权或美式不触碰二元期权的现金返还方式PaymentType一定是到期支付Expire"
        self.discrete_obs_interval = discrete_obs_interval  # 连续观察=None；均匀离散观察=观察时间间隔
        # if self.exercise_type == ExerciseType.European:
        #     assert self.discrete_obs_interval is None, "ValueError: 欧式二元期权，观察时间间隔只能为None." # 其实没影响
        self.s0 = s0
        self.status = status
        self.stop_date = self.end_date  # 停止日期，默认等于到期日。美式二元如果提前行权，停止日期更新为提前行权日期
        if engine is not None:
            self.set_pricing_engine(engine)
        else:
            if engine_method is None:
                default_engine = AnalyticCashOrNothingEngine  # 默认Analytic定价引擎
            elif engine_method == "Analytic":
                default_engine = AnalyticCashOrNothingEngine
            elif engine_method in ["PDE", "FDM"]:
                default_engine = FdmDigitalEngine
            elif engine_method in ["MC", "MonteCarlo"]:
                default_engine = MCDigitalEngine
            elif engine_method == "QUAD":
                default_engine = QuadDigitalEngine
            elif engine_method == "TREE":
                default_engine = BiTreeDigitalEngine
            else:
                raise NotImplementedError(
                    f"不支持的engine_method{engine_method}, {self.__repr__()}仅支持Analytic/MC/PDE/QUAD/TREE")
            if stoch_process is not None:
                self.set_pricing_engine(default_engine(stoch_process))
            elif s is not None and r is not None and q is not None and vol is not None:
                self.set_pricing_engine(default_engine(s=s, r=r, q=q, vol=vol))

    def set_pricing_engine(self, engine):
        """设置定价引擎，同时将自己注册为观察者。若已有定价引擎，先将自己从原定价引擎的观察者列表中移除"""
        with suppress(AttributeError, ValueError):
            self.engine.process.spot.remove_observer(self)
        self.engine = engine
        self.engine.process.spot.add_observer(self)
        logging.info(f"{self}当前定价方法为{engine.engine_type.value}")

    def remove_self(self):
        """删除对象自己，del自己之前，先将自己从被观察者的列表中移除"""
        self.engine.process.spot.remove_observer(self)
        del self

    def update(self, observable, *args, **kwargs):
        """收到标的价格变化的通知时，自动更新是否已经触碰障碍"""
        if global_evaluation_date() > self.stop_date:  # 如果估值日已经过了终止日，维持原来的状态
            return
        if global_auto_update_status() and observable == self.engine.process.spot:
            # 如果是二元欧式，且估值日是到期日时，更新状态 todo: 暂时只支持日频行情更新，即估值日的第一次标的价格变化即视为收盘价更新
            if self.exercise_type == ExerciseType.European and global_evaluation_date() == self.end_date:
                self.change_status(observable.data)
            # 二元美式/一触即付，连续观察或每日离散观察，每次标的价格变化，均更新状态
            elif self.exercise_type == ExerciseType.American:
                # todo: 均匀离散观察，只支持每日观察，暂不支持其他观察频率。即每次标的价格变化，均更新状态
                self.change_status(observable.data)

    def change_status(self, spot):
        """获取状态变化"""
        if self.status == StatusType.NoTouch:
            if self.callput == CallPut.Call and spot >= self.strike:
                self.status = StatusType.UpTouch
                if self.payment_type == PaymentType.Hit:  # 若美式二元提前终止
                    self.stop_date = global_evaluation_date()
            elif self.callput == CallPut.Put and spot <= self.strike:
                self.status = StatusType.DownTouch
                if self.payment_type == PaymentType.Hit:  # 若美式二元提前终止
                    self.stop_date = global_evaluation_date()
        else:
            return

    def __repr__(self):
        """返回期权的描述"""
        if self.exercise_type == ExerciseType.European:
            return f"欧式二元{self.callput.name}期权"
        elif self.exercise_type == ExerciseType.American:
            if self.discrete_obs_interval is None:
                obs_type = "连续观察"
            else:
                obs_type = "离散观察"
            if self.payment_type == PaymentType.Hit:
                digital_option = "美式二元(立即支付)"
            else:
                digital_option = "一触即付(到期支付)"
            return f"{obs_type}{digital_option}{self.callput.name}期权"
        else:
            raise ValueError("二元（数字）期权的exercise_type参数只支持欧式或美式")


    @time_this
    def price(self, t: datetime.date = None, spot=None):
        """计算期权价格
        Args:
            t: datetime.date，计算期权价格的日期
            spot: float，标的价格
        Returns: 期权现值
        """
        self.validate_parameters(t=t)
        calculate_date = global_evaluation_date() if t is None else t
        if self.status != StatusType.NoTouch:  # 如果已经触碰障碍，则直接返回行权收益的现值
            if self.touch_type == TouchType.NoTouch:
                return 0  # 单边二元属性固定为Touch，这里走不到
            elif self.touch_type == TouchType.Touch:
                if self.payment_type == PaymentType.Hit:  # 立即支付
                    if self.rebate_annual:  # 年化百分比
                        elapsed_time = (calculate_date - self.start_date).days / self.annual_days.value
                        _rebate = self.rebate * self.s0 * elapsed_time
                    else:  # 绝对数值
                        _rebate = self.rebate
                    return self.rebate
                elif self.payment_type == PaymentType.Expire:  # 到期支付
                    if self.rebate_annual:  # 年化百分比
                        tenor = (self.end_date - self.start_date).days / self.annual_days.value  # 从起始日到终止日的自然日时间（年）
                        _rebate = self.rebate * self.s0 * tenor
                    else:  # 绝对数值
                        _rebate = self.rebate
                    _maturity = (self.end_date - calculate_date).days / self.annual_days.value
                    return _rebate * self.engine.process.interest.disc_factor(_maturity)
                else:
                    raise ValueError(f"未知的支付方式{self.payment_type}")
        else:  # 尚未触碰障碍，正常定价
            if self.engine.engine_type == EngineType.PdeEngine:  # 接口特殊是因为PDE引擎兼容了单双边二元
                if self.callput == CallPut.Call:
                    bound = (None, self.strike)
                else:  # Put
                    bound = (self.strike, None)
                price = self.engine.calc_present_value(prod=self, t=t, spot=spot, bound=bound,
                                                       rebate=(self.rebate, self.rebate))
            else:
                price = self.engine.calc_present_value(prod=self, t=t, spot=spot)
        return price
