"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OpenAICompatibleProxy = void 0;
const express_1 = __importDefault(require("express"));
const compressor_1 = require("../token-saver/compressor");
const react_loop_1 = require("../agentic/react-loop");
const tool_executor_1 = require("../agentic/tool-executor");
const planner_1 = require("../agentic/planner");
const model_router_1 = require("../agentic/model-router");
const path_1 = __importDefault(require("path"));
class OpenAICompatibleProxy {
    constructor(accountManager, port = 20129) {
        this.app = (0, express_1.default)();
        this.accountManager = accountManager;
        this.port = port;
        this.compressor = new compressor_1.TokenCompressor();
        const executor = new tool_executor_1.ToolExecutor();
        const planner = new planner_1.Planner();
        const router = new model_router_1.ModelRouter();
        this.agenticLoop = new react_loop_1.ReactLoop(executor, planner, router);
        this.setupMiddleware();
        this.setupWebUI();
        this.setupRoutes();
    }
    setupMiddleware() {
        this.app.use(express_1.default.json());
    }
    setupWebUI() {
        const webDistPath = path_1.default.join(__dirname, "../../web/dist");
        this.app.use(express_1.default.static(webDistPath));
        this.app.get("/api/accounts", (req, res) => {
            res.json(this.accountManager.listAccounts());
        });
        this.app.get("/api/status", (req, res) => {
            res.json({ status: "running", port: this.port });
        });
        this.app.get("*", (req, res) => {
            res.sendFile(path_1.default.join(webDistPath, "index.html"), (err) => {
                if (err) {
                    res.status(404).json({
                        error: {
                            message: "Web UI not found. Run npm run build:web first.",
                            type: "not_found",
                            param: null,
                            code: 404
                        }
                    });
                }
            });
        });
    }
    setupRoutes() {
        this.app.post("/v1/chat/completions", async (req, res) => {
            try {
                const account = this.accountManager.getNextAccount();
                if (!account) {
                    res.status(503).json({
                        error: {
                            message: "No active accounts available",
                            type: "service_unavailable",
                            param: null,
                            code: 503
                        }
                    });
                    return;
                }
                const { messages, model, stream = false } = req.body;
                const compressedMessages = this.compressor.compressConversation(messages || []);
                const lastMessage = messages?.[messages.length - 1]?.content || "";
                const isAgentic = lastMessage.includes("implement") || lastMessage.includes("fix");
                if (isAgentic) {
                    const result = await this.agenticLoop.execute(lastMessage);
                    res.json({
                        id: `chatcmpl-${Math.random().toString(36).substr(2, 9)}`,
                        object: "chat.completion",
                        created: Math.floor(Date.now() / 1000),
                        model: model || "gemini-pro",
                        choices: [
                            {
                                index: 0,
                                message: {
                                    role: "assistant",
                                    content: result.output
                                },
                                finish_reason: "stop"
                            }
                        ],
                        usage: {
                            prompt_tokens: this.compressor.estimateTokens(JSON.stringify(compressedMessages)),
                            completion_tokens: this.compressor.estimateTokens(result.output),
                            total_tokens: 0
                        }
                    });
                    return;
                }
                res.json({
                    id: `chatcmpl-${Math.random().toString(36).substr(2, 9)}`,
                    object: "chat.completion",
                    created: Math.floor(Date.now() / 1000),
                    model: model || "gemini-pro",
                    choices: [
                        {
                            index: 0,
                            message: {
                                role: "assistant",
                                content: "This is a placeholder response from Frouter. The full Gemini integration would be implemented here."
                            },
                            finish_reason: "stop"
                        }
                    ],
                    usage: {
                        prompt_tokens: 10,
                        completion_tokens: 5,
                        total_tokens: 15
                    }
                });
            }
            catch (error) {
                console.error("Error in chat completions:", error);
                res.status(500).json({
                    error: {
                        message: "Internal server error",
                        type: "server_error",
                        param: null,
                        code: 500
                    }
                });
            }
        });
        this.app.get("/v1/models", (req, res) => {
            res.json({
                object: "list",
                data: [
                    {
                        id: "gemini-pro",
                        object: "model",
                        created: 1686935002,
                        owned_by: "frouter"
                    },
                    {
                        id: "gemini-flash",
                        object: "model",
                        created: 1686935002,
                        owned_by: "frouter"
                    }
                ]
            });
        });
    }
    async start() {
        return new Promise((resolve, reject) => {
            this.server = this.app.listen(this.port, () => {
                console.log(`Frouter proxy running on http://localhost:${this.port}`);
                console.log(`Ready to accept requests at http://localhost:${this.port}/v1/chat/completions`);
                console.log(`Dashboard at http://localhost:${this.port}/`);
                resolve();
            });
            this.server.on("error", (err) => {
                if (err.code === "EADDRINUSE") {
                    console.error(`Port ${this.port} is already in use. Try a different port.`);
                }
                else {
                    console.error(`Server error:`, err);
                }
                reject(err);
            });
        });
    }
    async stop() {
        return new Promise((resolve, reject) => {
            if (this.server) {
                this.server.close((err) => {
                    if (err) {
                        reject(err);
                    }
                    else {
                        console.log("Frouter proxy server stopped");
                        resolve();
                    }
                });
            }
            else {
                resolve();
            }
        });
    }
}
exports.OpenAICompatibleProxy = OpenAICompatibleProxy;
//# sourceMappingURL=openai-compat.js.map