"""Read weekly fund signals, then optionally submit one real TianTian subscription.

The budget is NEW money for this decision, not the whole account's target NAV.
Credentials are entered locally and are never accepted as command-line arguments.
"""

import argparse
import json
import re
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation, ROUND_DOWN
from getpass import getpass
from importlib import import_module

from tokoyo import (
    FundAccount, FundTrader, OrderError, OrderSide, OrderStatus, PaymentPassword,
    TianTianGateway, TianTianPasswordAuthorizer, login,
)
from tokoyo.market import MarketDataError, aggregate_nav, daily_nav


def choose_weights(recent):
    """The same 12-period momentum rule used in the introductory backtest."""
    if len(recent) < 12:
        return None
    momentum = (1 + recent).prod() - 1
    if momentum.mean() <= 0:
        return {}
    return {str(momentum.idxmax()): 0.8}


def choose_fund(ctx):
    return choose_weights(ctx.returns(lookback=12))


def weekly_signal(funds, nav_through):
    import pandas as pd

    series = {}
    latest_periods = set()
    for fund in funds:
        daily = daily_nav(fund, start=nav_through - timedelta(days=200), end=nav_through)
        if daily.empty or len(daily) < 2:
            raise ValueError(f"Insufficient daily NAV for {fund}")
        growth = daily["daily_return"].copy()
        if growth.iloc[1:].isna().any() or not growth.iloc[1:].between(-1, float("inf"), inclusive="neither").all():
            raise ValueError(f"Missing or invalid daily returns for {fund}")
        growth.iloc[0] = 0.0
        research = daily[["date", "nav"]].copy()
        research["nav"] = (1 + growth).cumprod()
        weekly = aggregate_nav(research, "week", end=nav_through)
        if weekly.empty:
            raise ValueError(f"No completed weekly bars for {fund}")
        series[fund] = weekly.set_index("period_end")["close"]
        latest_periods.add(weekly["period_end"].iloc[-1])
    if len(latest_periods) != 1:
        raise ValueError("Funds do not end on the same completed week")
    panel = pd.DataFrame(series).dropna().sort_index()
    if panel.empty or panel.index[-1] != next(iter(latest_periods)):
        raise ValueError("No matching completed week across funds")
    recent = panel.pct_change(fill_method=None).iloc[1:].tail(12)
    return panel.index[-1].date(), choose_weights(recent)


def read_payment_password():
    import msvcrt

    digits = bytearray()
    print("Six-digit payment password (hidden): ", end="", flush=True)
    try:
        while True:
            key = msvcrt.getwch()
            if key in {"\x00", "\xe0"}:
                msvcrt.getwch()
            elif key in {"\x03", "\x1b"}:
                raise KeyboardInterrupt
            elif key == "\r" and len(digits) == 6:
                return digits
            elif key == "\b" and digits:
                digits[-1] = 0
                digits.pop()
            elif "0" <= key <= "9" and len(digits) < 6:
                digits.append(ord(key))
    except BaseException:
        for index in range(len(digits)):
            digits[index] = 0
        raise
    finally:
        print()


def money(value):
    try:
        amount = Decimal(value)
        if not amount.is_finite() or amount <= 0:
            raise argparse.ArgumentTypeError("Budget must be positive and finite")
        rounded = amount.quantize(Decimal("0.01"))
    except InvalidOperation:
        raise argparse.ArgumentTypeError("Budget must be a decimal amount") from None
    if amount != rounded:
        raise argparse.ArgumentTypeError("Budget must be positive with at most two decimal places")
    return amount


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--funds", nargs="+", default=["013835", "000001"])
    parser.add_argument("--budget", required=True, type=money, help="New subscription budget in CNY")
    parser.add_argument("--nav-through", required=True, type=date.fromisoformat, help="Confirmed published NAV cutoff")
    parser.add_argument("--account", help="Stable local alias for the actual account")
    parser.add_argument("--provider", help="Module with an authorized login() -> TianTianSession")
    parser.add_argument("--strategy-id", default="first-weekly-subscription-v1")
    parser.add_argument("--db", default="first-tiantian.sqlite3")
    parser.add_argument("--submit", action="store_true", help="Submit a real order when the signal selects a fund")
    args = parser.parse_args()
    if len(set(args.funds)) != len(args.funds) or any(not re.fullmatch(r"[0-9]{6}", fund) for fund in args.funds):
        parser.error("Use unique six-digit fund codes")
    if not args.strategy_id.strip():
        parser.error("Use a stable nonempty strategy ID")
    today = datetime.now(timezone(timedelta(hours=8))).date()
    if args.nav_through > today:
        parser.error("NAV cutoff cannot be in the future")
    if args.submit and not args.account:
        parser.error("Real submission requires --account")
    if args.submit and today - args.nav_through > timedelta(days=7):
        parser.error("For live submission, verify published NAV and use a cutoff within the last 7 calendar days")

    period_end, weights = weekly_signal(args.funds, args.nav_through)
    print(json.dumps({"period_end": period_end.isoformat(), "nav_through": args.nav_through.isoformat(), "weights": weights}, ensure_ascii=False))
    if weights is None:
        print("Not enough completed weeks; no order requested")
        return
    if not weights:
        print("Cash signal; this subscription-only example places no order")
        return
    fund, weight = next(iter(weights.items()))
    amount = (args.budget * Decimal(str(weight))).quantize(Decimal("0.01"), rounding=ROUND_DOWN)
    if amount <= 0:
        raise ValueError("Subscription amount rounds to zero")
    print(f"Subscription instruction: fund={fund}, amount_cny={amount}")
    if not args.submit:
        print("Signal analysis only. Add --submit to use the actual TianTian order API")
        return

    account = FundAccount(args.account)
    flow = import_module(args.provider).login if args.provider else None
    transport = login(account, flow)
    bank_account_no = getpass("Bound BankAccountNo (platform payment identifier): ")
    with PaymentPassword(read_payment_password()) as password:
        authorizer = TianTianPasswordAuthorizer(transport, password, bank_account_no)
        gateway = TianTianGateway(transport, authorizer)
        with FundTrader(gateway, db_path=args.db, enable_live=True) as trader:
            order_id = trader.order_fund(
                account, fund, OrderSide.SUBSCRIBE, amount=amount,
                client_order_id=f"{args.strategy_id}:{period_end.isoformat()}:subscribe",
                strategy_name=args.strategy_id, order_remark="new subscription budget",
            )
            order = trader.query_fund_order(account, order_id)
            print(json.dumps({"order_id": order.order_id, "status": order.status.value, "broker_order_id": order.broker_order_id}, ensure_ascii=False))
            if order.status is OrderStatus.PAYMENT_REQUIRED:
                print("Continue the official bank payment flow; see the bank payment confirmation documentation")
            elif order.status is OrderStatus.UNKNOWN:
                print("Submission outcome is unknown; reconcile with official records before any further order")


if __name__ == "__main__":
    try:
        main()
    except (KeyboardInterrupt, EOFError):
        pass
    except (OSError, OrderError, MarketDataError, ValueError) as error:
        raise SystemExit(str(error)) from None
