// Electron API 类型定义

// ===========================================================================
// Share 相关
// ===========================================================================

interface ShareEntry {
  id: string;
  sessionId: string;
  walletName: string;
  partyId: string;
  partyIndex: number;
  threshold: { t: number; n: number };
  publicKey: string;
  createdAt: string;
  lastUsedAt?: string;
  participants: Array<{ partyId: string; name: string }>;
  // 兼容页面组件的 metadata 格式
  metadata: {
    participants: Array<{ partyId: string; name: string }>;
  };
}

interface ShareWithRawData extends ShareEntry {
  rawShare: string;
}

// ===========================================================================
// 派生地址相关
// ===========================================================================

interface DerivedAddress {
  id: string;
  shareId: string;
  chain: string;
  chainName: string;
  derivationPath: string;
  address: string;
  publicKeyHex: string;
  createdAt: string;
}

interface ChainConfig {
  name: string;
  prefix: string;
  coinType: number;
  curve: 'secp256k1' | 'ed25519';
  derivationPath: string;
}

// ===========================================================================
// 签名历史相关
// ===========================================================================

interface SigningHistoryEntry {
  id: string;
  shareId: string;
  sessionId: string;
  messageHash: string;
  signature: string | null;
  status: 'pending' | 'in_progress' | 'completed' | 'failed';
  errorMessage: string | null;
  createdAt: string;
  completedAt: string | null;
}

// ===========================================================================
// 会话相关
// ===========================================================================

interface SessionInfo {
  sessionId: string;
  walletName: string;
  threshold: { t: number; n: number };
  initiator: string;
  createdAt: string;
  currentParticipants: number;
}

interface Participant {
  partyId: string;
  name: string;
  status: 'waiting' | 'ready' | 'processing' | 'completed' | 'failed';
  joinedAt: string;
}

interface SessionState {
  sessionId: string;
  walletName: string;
  threshold: { t: number; n: number };
  status: 'waiting' | 'ready' | 'processing' | 'completed' | 'failed';
  participants: Participant[];
  currentRound: number;
  totalRounds: number;
  publicKey?: string;
  error?: string;
}

// ===========================================================================
// 设置相关
// ===========================================================================

interface Settings {
  messageRouterUrl: string;
  autoBackup: boolean;
  backupPath: string;
}

// ===========================================================================
// API 参数和结果类型
// ===========================================================================

interface CreateSessionParams {
  walletName: string;
  thresholdT: number;
  thresholdN: number;
  initiatorName: string;
}

interface CreateSessionResult {
  success: boolean;
  sessionId?: string;
  inviteCode?: string;
  error?: string;
}

interface JoinSessionResult {
  success: boolean;
  error?: string;
}

interface ValidateInviteCodeResult {
  success: boolean;
  sessionInfo?: SessionInfo;
  joinToken?: string;
  error?: string;
}

interface GetSessionStatusResult {
  success: boolean;
  session?: SessionState;
  error?: string;
}

interface TestConnectionResult {
  success: boolean;
  error?: string;
}

// 已注册的参与方
interface RegisteredParty {
  partyId: string;
  role: string;
  online: boolean;
  registeredAt: string;
  lastSeenAt: string;
}

interface GetRegisteredPartiesResult {
  success: boolean;
  parties: RegisteredParty[];
  error?: string;
}

interface SessionEvent {
  type: 'participant_joined' | 'status_changed' | 'completed' | 'failed';
  participant?: Participant;
  status?: string;
  currentRound?: number;
  publicKey?: string;
  error?: string;
}

// 签名相关类型
interface SigningSession {
  sessionId: string;
  walletName: string;
  messageHash: string;
  threshold: { t: number; n: number };
  currentParticipants: number;
  initiator: string;
}

interface ValidateSigningSessionResult {
  success: boolean;
  session?: SigningSession;
  error?: string;
}

interface JoinSigningSessionParams {
  sessionId: string;
  shareId: string;
  password: string;
}

interface JoinSigningSessionResult {
  success: boolean;
  partyId?: string;
  partyIndex?: number;
  error?: string;
}

// Account 服务相关类型
interface CreateSignSessionParams {
  shareId: string;
  password: string;
  messageHash: string;
  initiatorName?: string;
}

interface CreateSignSessionResult {
  success: boolean;
  sessionId?: string;
  inviteCode?: string;
  expiresAt?: number;
  joinToken?: string;
  error?: string;
}

interface SignSessionInfo {
  sessionId: string;
  keygenSessionId: string;
  walletName: string;
  messageHash: string;
  thresholdT: number;
  status: string;
  inviteCode: string;
  expiresAt: number;
  parties: Array<{ party_id: string; party_index: number }>;
  joinedCount: number;
}

interface GetSignSessionByInviteCodeResult {
  success: boolean;
  session?: SignSessionInfo;
  error?: string;
}

interface AccountHealthCheckResult {
  success: boolean;
  data?: { status: string; service: string };
  error?: string;
}

interface AccountTestConnectionResult {
  success: boolean;
  error?: string;
}

interface SigningProgressEvent {
  type: 'progress' | 'completed' | 'failed';
  current?: number;
  total?: number;
  signature?: string;
  error?: string;
}

interface ListSharesResult {
  success: boolean;
  data?: ShareEntry[];
  error?: string;
}

interface SaveShareResult {
  success: boolean;
  data?: ShareEntry;
  error?: string;
}

interface ExportShareResult {
  success: boolean;
  data?: ArrayBuffer;
  filePath?: string;
  error?: string;
}

interface DeriveAddressResult {
  success: boolean;
  data?: DerivedAddress;
  error?: string;
}

interface DeriveAllAddressesResult {
  success: boolean;
  data?: DerivedAddress[];
  error?: string;
}

interface ListAddressesResult {
  success: boolean;
  data?: DerivedAddress[];
  error?: string;
}

interface GetSigningHistoryResult {
  success: boolean;
  data?: SigningHistoryEntry[];
  error?: string;
}

// ===========================================================================
// Kava 相关类型
// ===========================================================================

interface KavaBalance {
  denom: string;
  amount: string;
  formatted: string;
}

interface KavaAccountInfo {
  address: string;
  accountNumber: number;
  sequence: number;
  balances: KavaBalance[];
}

interface KavaUnsignedTx {
  signBytes: Uint8Array;
  signBytesHex: string;
  txBodyBytes: Uint8Array;
  authInfoBytes: Uint8Array;
  accountNumber: number;
  sequence: number;
  chainId: string;
  from: string;
  to: string;
  amount: string;
  denom: string;
  memo: string;
  fee: string;
  gasLimit: number;
}

interface KavaTxBroadcastResult {
  success: boolean;
  txHash?: string;
  code?: number;
  rawLog?: string;
  gasUsed?: string;
  gasWanted?: string;
  height?: string;
  error?: string;
}

interface KavaTxStatus {
  found: boolean;
  status: 'pending' | 'success' | 'failed';
  height?: number;
  code?: number;
  rawLog?: string;
}

interface KavaConfig {
  lcdEndpoint: string;
  rpcEndpoint: string;
  chainId: string;
  prefix: string;
  denom: string;
  gasPrice: number;
}

interface GetKavaBalanceResult {
  success: boolean;
  data?: KavaBalance;
  error?: string;
}

interface GetAllKavaBalancesResult {
  success: boolean;
  data?: KavaBalance[];
  error?: string;
}

interface GetKavaAccountInfoResult {
  success: boolean;
  data?: KavaAccountInfo;
  error?: string;
}

interface BuildKavaSendTxResult {
  success: boolean;
  data?: KavaUnsignedTx;
  error?: string;
}

interface CompleteTxAndBroadcastResult {
  success: boolean;
  data?: KavaTxBroadcastResult;
  error?: string;
}

interface GetKavaTxStatusResult {
  success: boolean;
  data?: KavaTxStatus;
  error?: string;
}

interface KavaHealthCheckResult {
  success: boolean;
  data?: {
    ok: boolean;
    latency?: number;
    error?: string;
  };
  error?: string;
}

// ===========================================================================
// Electron API 接口
// ===========================================================================

// ===========================================================================
// Co-Sign 相关类型
// ===========================================================================

interface CoSignSessionInfo {
  sessionId: string;
  keygenSessionId: string;
  walletName: string;
  messageHash: string;
  threshold: { t: number; n: number };
  status: string;
  currentParticipants: number;
  parties?: Array<{ party_id: string; party_index: number }>;
}

interface CreateCoSignSessionParams {
  shareId: string;
  sharePassword: string;
  messageHash: string;
  initiatorName?: string;
}

interface CreateCoSignSessionResult {
  success: boolean;
  sessionId?: string;
  inviteCode?: string;
  walletName?: string;
  expiresAt?: string;
  error?: string;
}

interface ValidateCoSignInviteCodeResult {
  success: boolean;
  sessionInfo?: CoSignSessionInfo;
  joinToken?: string;
  error?: string;
}

interface JoinCoSignSessionParams {
  sessionId: string;
  shareId: string;
  sharePassword: string;
  joinToken: string;
  walletName?: string;
  messageHash: string;
  threshold: { t: number; n: number };
  parties?: Array<{ party_id: string; party_index: number }>;
}

interface JoinCoSignSessionResult {
  success: boolean;
  data?: unknown;
  error?: string;
}

interface GetCoSignSessionStatusResult {
  success: boolean;
  session?: {
    sessionId: string;
    status: string;
    joinedCount: number;
    threshold: { t: number; n: number };
    participants: Array<{
      partyId: string;
      partyIndex: number;
      name: string;
      status: string;
    }>;
    messageHash: string;
    walletName: string;
  };
  error?: string;
}

interface CoSignSessionEvent {
  type: 'participant_joined' | 'status_changed' | 'all_joined' | 'progress' | 'completed' | 'failed' | 'sign_start_timeout';
  participant?: {
    partyId: string;
    name: string;
    status: string;
  };
  status?: string;
  round?: number;
  totalRounds?: number;
  signature?: string;
  error?: string;
}

interface ElectronAPI {
  // Account 服务相关 (HTTP API)
  account: {
    createSignSession: (params: CreateSignSessionParams) => Promise<CreateSignSessionResult>;
    getSignSessionByInviteCode: (inviteCode: string) => Promise<GetSignSessionByInviteCodeResult>;
    healthCheck: () => Promise<AccountHealthCheckResult>;
    testConnection: () => Promise<AccountTestConnectionResult>;
    updateUrl: (url: string) => Promise<{ success: boolean; error?: string }>;
    getUrl: () => Promise<string>;
  };

  // gRPC 相关
  grpc: {
    createSession: (params: CreateSessionParams) => Promise<CreateSessionResult>;
    joinSession: (params: {
      sessionId: string;
      partyId: string;
      joinToken: string;
      walletName?: string;
    }) => Promise<JoinSessionResult>;
    validateInviteCode: (code: string) => Promise<ValidateInviteCodeResult>;
    getSessionStatus: (sessionId: string) => Promise<GetSessionStatusResult>;
    subscribeSessionEvents: (sessionId: string, callback: (event: SessionEvent) => void) => () => void;
    testConnection: (url: string) => Promise<TestConnectionResult>;
    // 获取已注册的参与方列表
    getRegisteredParties: (roleFilter?: string, onlyOnline?: boolean) => Promise<GetRegisteredPartiesResult>;
    // 获取当前 partyId
    getPartyId: () => Promise<{ success: boolean; partyId: string | null; error?: string }>;
    // 检查连接状态
    isConnected: () => Promise<{ success: boolean; connected: boolean; error?: string }>;
    // 连接到 Message Router
    connect: (url: string) => Promise<{ success: boolean; error?: string }>;
    // 注册为参与方
    register: (partyId: string, role: string) => Promise<{ success: boolean; error?: string }>;
    // 签名相关
    validateSigningSession: (code: string) => Promise<ValidateSigningSessionResult>;
    joinSigningSession: (params: JoinSigningSessionParams) => Promise<JoinSigningSessionResult>;
    subscribeSigningProgress: (sessionId: string, callback: (event: SigningProgressEvent) => void) => () => void;
  };

  // 存储相关 (SQLite)
  storage: {
    saveShare: (share: {
      sessionId: string;
      walletName: string;
      partyId: string;
      partyIndex: number;
      threshold: { t: number; n: number };
      publicKey: string;
      rawShare: string;
      participants?: Array<{ partyId: string; name: string }>;
    }, password: string) => Promise<SaveShareResult>;
    listShares: () => Promise<ListSharesResult>;
    getShare: (id: string, password: string) => Promise<ShareWithRawData | null>;
    exportShare: (id: string, password: string) => Promise<ExportShareResult>;
    importShare: (filePath: string, password: string) => Promise<{ success: boolean; share?: ShareEntry; error?: string }>;
    deleteShare: (id: string) => Promise<{ success: boolean; error?: string }>;
    getSettings: () => Promise<Settings | null>;
    saveSettings: (settings: Partial<Settings>) => Promise<{ success: boolean; error?: string }>;
  };

  // 地址派生相关
  address: {
    derive: (shareId: string, chain: string, password: string) => Promise<DeriveAddressResult>;
    deriveAll: (shareId: string, password: string) => Promise<DeriveAllAddressesResult>;
    list: (shareId: string) => Promise<ListAddressesResult>;
    getSupportedChains: () => Promise<ChainConfig[]>;
  };

  // 签名历史相关
  signing: {
    getHistory: (shareId: string) => Promise<GetSigningHistoryResult>;
  };

  // Kava 区块链相关
  kava: {
    getBalance: (address: string) => Promise<GetKavaBalanceResult>;
    getAllBalances: (address: string) => Promise<GetAllKavaBalancesResult>;
    getAccountInfo: (address: string) => Promise<GetKavaAccountInfoResult>;
    buildSendTx: (params: {
      fromAddress: string;
      toAddress: string;
      amount: string;
      publicKeyHex: string;
      memo?: string;
    }) => Promise<BuildKavaSendTxResult>;
    completeTxAndBroadcast: (params: {
      unsignedTx: KavaUnsignedTx;
      signatureHex: string;
    }) => Promise<CompleteTxAndBroadcastResult>;
    getTxStatus: (txHash: string) => Promise<GetKavaTxStatusResult>;
    getConfig: () => Promise<KavaConfig>;
    updateConfig: (config: Partial<KavaConfig>) => Promise<{ success: boolean; error?: string }>;
    healthCheck: () => Promise<KavaHealthCheckResult>;
    switchNetwork: (network: 'mainnet' | 'testnet') => Promise<{ success: boolean; network?: string; error?: string }>;
    getNetwork: () => Promise<{ network: 'mainnet' | 'testnet' }>;
  };

  // 对话框相关
  dialog: {
    selectDirectory: () => Promise<string | null>;
    selectFile: (filters?: { name: string; extensions: string[] }[]) => Promise<string | null>;
    saveFile: (defaultPath?: string, filters?: { name: string; extensions: string[] }[]) => Promise<string | null>;
  };

  // 调试相关
  debug?: {
    subscribeLogs: (callback: (event: unknown, data: { level: string; source: string; message: string }) => void) => void;
    unsubscribeLogs: () => void;
    log: (level: string, source: string, message: string) => void;
  };

  // Co-Sign 相关 (多方协作签名)
  cosign: {
    createSession: (params: CreateCoSignSessionParams) => Promise<CreateCoSignSessionResult>;
    validateInviteCode: (code: string) => Promise<ValidateCoSignInviteCodeResult>;
    joinSession: (params: JoinCoSignSessionParams) => Promise<JoinCoSignSessionResult>;
    getSessionStatus: (sessionId: string) => Promise<GetCoSignSessionStatusResult>;
    subscribeSessionEvents: (sessionId: string, callback: (event: CoSignSessionEvent) => void) => () => void;
  };
}

declare global {
  interface Window {
    electronAPI: ElectronAPI;
  }
}

export {};
