import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import model.AppConfig
import model.KisSession
import network.LlamaServerManager
import org.jetbrains.exposed.sql.selectAll
import ui.DashboardScreen
import ui.SettingsScreen

// 화면 상태 정의
enum class AppScreen { Settings, Dashboard }

fun main() = application {
    // 앱 실행 시 필요한 바이너리 경로 (실행 파일 위치)
    val binPath = "./src/main/resources/bin/llama-server"

    Window(onCloseRequest = ::exitApplication, title = "KIS AI 자동매매") {
        var currentScreen by remember { mutableStateOf(AppScreen.Settings) }
        var isLoaded by remember { mutableStateOf(false) }
        val scope = rememberCoroutineScope()

        // 1. 앱 시작 시 DB에서 마지막 설정 로드 (KisSession에 주입)
        LaunchedEffect(Unit) {
            DatabaseFactory.init()
            transaction {
                ConfigTable.selectAll().lastOrNull()?.let {
                    KisSession.config = AppConfig(
                        realAppKey = it[ConfigTable.realAppKey],
                        realSecretKey = it[ConfigTable.realSecretKey],
                        realAccountNo = it[ConfigTable.realAccountNo],
                        vtsAppKey = it[ConfigTable.vtsAppKey],
                        vtsSecretKey = it[ConfigTable.vtsSecretKey],
                        vtsAccountNo = it[ConfigTable.vtsAccountNo],
                        isSimulation = it[ConfigTable.isSimulation],
                        htsId = it[ConfigTable.htsId],
                        modelPath = it[ConfigTable.modelPath]
                    )
                }
            }


            isLoaded = true
        }

        if (!isLoaded) {
            // 로딩 중 표시
            CircularProgressIndicator()
        } else {
            when (currentScreen) {
                AppScreen.Settings -> {
                    SettingsScreen(
                        onAuthSuccess = {
                            // 2. 설정 및 인증 완료 시점의 처리
                            val config = KisSession.config

                            // LLM 서버 시작 (설정된 모델 경로 사용)
                            if (config.modelPath.isNotEmpty()) {
                                LlamaServerManager.startServer(binPath, config.modelPath)
                            }

                            // 대시보드로 화면 전환
                            currentScreen = AppScreen.Dashboard
                        }
                    )
                }
                AppScreen.Dashboard -> {
                    DashboardScreen()
                }
            }
        }
    }
}