import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Check for config.yml
        File configFile = new File("config.yml");
        if (!configFile.exists()) {
            System.out.println("No config.yml found. Starting first-time setup...");
            firstTimeSetup();
        }

        // Load config and format
        try {
            var config = ConfigLoader.loadConfig("config.yml");
            var format = FormatLoader.loadFormat("format.yml");

            int port = (int) config.getOrDefault("websocket_port", 3000);
            WebSocketServerApp wsServer = new WebSocketServerApp(port);
            wsServer.start();
            System.out.println("WebSocket server running on port " + port);

            // Initialize TikTok event listener (placeholder)

            TikTokEventListener tiktokListener = new TikTokEventListener(config, format, wsServer);
            // TODO: Connect TikTokLiveJava and wire up event callbacks to tiktokListener

        } catch (Exception e) {
            System.err.println("Failed to load config or start server: " + e.getMessage());
        }
    }

    private static void firstTimeSetup() {
        try (Scanner scanner = new Scanner(System.in)) {
            String username;
            do {
                System.out.print("Enter the TikTok username to follow (include @): ");
                username = scanner.nextLine();
            } while (!username.startsWith("@"));

            System.out.print("Enter websocket port (default 3000): ");
            String portInput = scanner.nextLine();
            int port = 3000;
            if (!portInput.isBlank()) {
                try {
                    port = Integer.parseInt(portInput);
                } catch (NumberFormatException e) {
                    System.out.println("Invalid port. Using default 3000.");
                }
            }

            // Write config.yml
            String config = "TIKTOK_USERNAME: '" + username + "'\nwebsocket_port: " + port + "\n";
            try {
                Files.writeString(Paths.get("config.yml"), config);
                System.out.println("config.yml created. Please edit it for more options as needed.");
            } catch (IOException e) {
                System.err.println("Failed to write config.yml: " + e.getMessage());
            }
        }
    }
}
