/**
 * RemoteLink Agent - Main Process
 * 
 * This is the main Electron process that:
 * - Creates the system tray icon
 * - Manages WebRTC connections
 * - Captures screen using desktopCapturer
 * - Handles input simulation
 */

import { app, BrowserWindow, Tray, Menu, desktopCapturer, ipcMain, screen } from 'electron'
import path from 'path'

let mainWindow: BrowserWindow | null = null
let tray: Tray | null = null

// Agent state
interface AgentState {
  accessKey: string | null
  isConnected: boolean
  currentSessionCode: string | null
  sessionCodeExpiry: Date | null
}

const agentState: AgentState = {
  accessKey: null,
  isConnected: false,
  currentSessionCode: null,
  sessionCodeExpiry: null,
}

const API_BASE_URL = process.env.API_BASE_URL || 'https://your-app.vercel.app'

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 400,
    height: 500,
    resizable: false,
    minimizable: true,
    maximizable: false,
    show: false,
    frame: false,
    skipTaskbar: true,
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      contextIsolation: true,
      nodeIntegration: false,
    },
  })

  mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))

  mainWindow.on('close', (event) => {
    event.preventDefault()
    mainWindow?.hide()
  })
}

function createTray() {
  const iconPath = path.join(__dirname, '../../assets/tray-icon.png')
  tray = new Tray(iconPath)

  const contextMenu = Menu.buildFromTemplate([
    {
      label: 'Open RemoteLink',
      click: () => {
        mainWindow?.show()
      },
    },
    {
      label: 'Generate Session Code',
      click: async () => {
        await generateSessionCode()
        mainWindow?.show()
      },
    },
    { type: 'separator' },
    {
      label: 'Settings',
      click: () => {
        mainWindow?.show()
        mainWindow?.webContents.send('navigate', 'settings')
      },
    },
    { type: 'separator' },
    {
      label: 'Quit',
      click: () => {
        app.quit()
      },
    },
  ])

  tray.setToolTip('RemoteLink Agent')
  tray.setContextMenu(contextMenu)

  tray.on('click', () => {
    mainWindow?.show()
  })
}

// Generate session code via API
async function generateSessionCode(): Promise<string | null> {
  if (!agentState.accessKey) {
    console.error('No access key configured')
    return null
  }

  try {
    const response = await fetch(`${API_BASE_URL}/api/agent/session-code`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ accessKey: agentState.accessKey }),
    })

    const data = await response.json()

    if (data.success) {
      agentState.currentSessionCode = data.code
      agentState.sessionCodeExpiry = new Date(data.expiresAt)
      
      // Notify renderer
      mainWindow?.webContents.send('session-code-generated', {
        code: data.code,
        expiresAt: data.expiresAt,
        expiresIn: data.expiresIn,
      })

      return data.code
    }
  } catch (error) {
    console.error('Failed to generate session code:', error)
  }

  return null
}

// Send heartbeat to server
async function sendHeartbeat() {
  if (!agentState.accessKey) return

  try {
    const response = await fetch(`${API_BASE_URL}/api/agent/heartbeat`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ accessKey: agentState.accessKey }),
    })

    const data = await response.json()

    if (data.pendingConnection) {
      // Handle incoming connection request
      mainWindow?.webContents.send('incoming-connection', data.pendingConnection)
    }
  } catch (error) {
    console.error('Heartbeat failed:', error)
  }
}

// Get available screen sources
async function getScreenSources() {
  const sources = await desktopCapturer.getSources({
    types: ['screen', 'window'],
    thumbnailSize: { width: 1920, height: 1080 },
  })

  return sources.map(source => ({
    id: source.id,
    name: source.name,
    thumbnail: source.thumbnail.toDataURL(),
  }))
}

// IPC Handlers
ipcMain.handle('get-screen-sources', getScreenSources)

ipcMain.handle('generate-session-code', generateSessionCode)

ipcMain.handle('get-agent-state', () => ({
  isConnected: agentState.isConnected,
  currentSessionCode: agentState.currentSessionCode,
  sessionCodeExpiry: agentState.sessionCodeExpiry?.toISOString(),
}))

ipcMain.handle('set-access-key', (_event, accessKey: string) => {
  agentState.accessKey = accessKey
  // Register with server
  registerAgent()
})

ipcMain.handle('get-monitors', () => {
  return screen.getAllDisplays().map((display, index) => ({
    id: display.id,
    index,
    label: `Display ${index + 1}`,
    width: display.size.width,
    height: display.size.height,
    primary: display.id === screen.getPrimaryDisplay().id,
  }))
})

// Register agent with server
async function registerAgent() {
  if (!agentState.accessKey) return

  try {
    const response = await fetch(`${API_BASE_URL}/api/agent/register`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        accessKey: agentState.accessKey,
        name: require('os').hostname(),
        hostname: require('os').hostname(),
        os: process.platform,
        osVersion: require('os').release(),
        agentVersion: app.getVersion(),
      }),
    })

    const data = await response.json()

    if (data.success) {
      agentState.isConnected = true
      mainWindow?.webContents.send('registered', data)
    }
  } catch (error) {
    console.error('Registration failed:', error)
  }
}

// App lifecycle
app.whenReady().then(() => {
  createWindow()
  createTray()

  // Start heartbeat interval
  setInterval(sendHeartbeat, 30000) // Every 30 seconds

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  // Don't quit on window close - keep running in tray
})

app.on('before-quit', () => {
  // Clean up
  tray?.destroy()
})
