import { SupportedChainIds, TAsset } from "@/types"
import { Address } from "../shared/types"
import {
  DEV_URL,
  LOGO_FALLBACK_URL,
  MORPHO_EXECUTOR_ID,
  PROD_URL,
} from "./constants"
import {
  MorphoVault,
  MorphoYieldAutomation,
  MorphoYieldAutomationLogResponse,
  MorphoYieldUserPosition,
  MorphoYieldVaultPosition,
} from "./types"
import assetsList from "@/baseNew.json"
import { isNotZero, truncateString } from "@/utils"
import { base } from "viem/chains"
import { BASE_CHAIN_ID, URL_API_KEY_PROD } from "@/constants"
import { ChatMessage } from "./hooks/useAiChat"

export const getBaseBackendUrl = () => {
  return PROD_URL
}

export function getMorphoYieldExecutorId(chainId: SupportedChainIds) {
  const origin = "DEVELOP"

  //   if (origin === "PROD") {
  //     return MORPHO_EXECUTOR_ID["PROD"][chainId];
  //   }
  //   if (origin === "STAGING") {
  //     return MORPHO_EXECUTOR_ID["STAGING"][chainId];
  //   }
  // if (origin === "DEVELOP") {
  //   return MORPHO_EXECUTOR_ID["PROD"][chainId];
  // }
  return MORPHO_EXECUTOR_ID["PROD"][chainId]
}

export const getFormattedDate = (
  date: Date,
  options: Intl.DateTimeFormatOptions | undefined = {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit",
  },
) => {
  return date.toLocaleString("en-US", options)
}

export const getGenericAsset = (
  address: Address,
  tokenChainId: SupportedChainIds,
  name?: string,
  decimal?: number,
  logo?: string,
): TAsset => {
  return {
    address,
    decimals: decimal || 18,
    chainId: tokenChainId,
    name: name || truncateString(address),
    logo: logo || LOGO_FALLBACK_URL,
    value: "0",
    prices: { default: 0 },
  }
}

export const getTokenData = (
  address: Address,
  chainId: SupportedChainIds,
): TAsset => {
  return (
    (assetsList.find(
      (token) => token.address.toLowerCase() === address.toLowerCase(),
    ) as TAsset) || getGenericAsset(address, chainId)
  )
}

export function getNextExecutionTime(
  initialDateStamp: string,
  intervalInSeconds: number,
): Date {
  const initialDate = new Date(initialDateStamp)
  const currentDate = new Date()
  const timeDifference = currentDate.getTime() - initialDate.getTime()
  const intervalInMillis = intervalInSeconds * 1000

  // Calculate how many intervals have passed
  const intervalsPassed = Math.ceil(timeDifference / intervalInMillis)
  // The next execution time is the initial date + intervalsPassed * interval duration
  const nextExecutionTime = new Date(
    initialDate.getTime() + intervalsPassed * intervalInMillis,
  )
  return nextExecutionTime
}

export const getBaseChainScanLink = (
  address: string,
  chainId?: SupportedChainIds,
  type: "address" | "tx" | "token" = "address",
) => `${base.blockExplorers.default.url}/${type}/${address}`

export const waitFor = async (ms = 1500) =>
  await new Promise((resolve) => setTimeout(resolve, ms))

// AI utils

export const generateFirstDepositPrompt = (
  tokenName: string,
  tokenAmount: string,
  tokenBalance: string,
  userEoa: string,
) => {
  return `i want to deposit ${tokenAmount} ${tokenName}`
}

export const generateDefaultMessage = (
  tokenAmount: string,
  tokenName: string,
  userHasPosition: boolean,
  isTokenAlreadyDeposited: boolean,
  minDepositAmount: number,
): ChatMessage => {
  // return { role: "assistant", content: mockMessage }
  if (isTokenAlreadyDeposited) {
    return {
      role: "assistant",
      content:
        "Welcome to Morpho Agent, Looks like you already have some amount deposited . Click on Start Agent to deploy your position",
    }
  }
  if (userHasPosition) {
    return {
      role: "assistant",
      content: "Welcome! How can I help you today?",
    }
  }
  if (
    !isNotZero(tokenAmount) ||
    Number(tokenAmount || "0") < minDepositAmount
  ) {
    return {
      role: "assistant",
      content: "Welcome to Morpho Agent, Enter your deposit amount to begin!",
    }
  }
  return {
    role: "assistant",
    content: `${` It looks like you're about to deposit. Click the button below to start prompting the Morpho Agent.
{
  "choicePrompts":["I want to deposit ${tokenAmount} ${tokenName}"]
}
    `}`,
  }
}

export const generateUserContent = ({
  tokenName,
  tokenAmount,
  tokenBalance,
  userPosition,
  eoa,
}: {
  tokenName: string
  tokenAmount: string
  tokenBalance: string
  userPosition: MorphoYieldUserPosition | null
  eoa: Address
}) => {
  console.log({ tokenName, tokenAmount, tokenBalance, userPosition, eoa })
  if (!userPosition) {
    return generateFirstDepositPrompt(tokenName, tokenAmount, tokenBalance, eoa)
  }
  const { amount, asset } = userPosition.tokenData
  return `User already has positioned opened of ${amount} ${asset.name} `
}
