"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountManager = void 0;
const uuid_1 = require("uuid");
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
const os_1 = __importDefault(require("os"));
class AccountManager {
    constructor(options = { storagePath: undefined, autoRotate: true }) {
        this.accounts = new Map();
        this.storagePath = options.storagePath || path_1.default.join(os_1.default.homedir(), ".frouter", "accounts.json");
        this.autoRotate = options.autoRotate ?? true;
        this.loadAccounts();
    }
    async ensureDir() {
        await promises_1.default.mkdir(path_1.default.dirname(this.storagePath), { recursive: true });
    }
    async loadAccounts() {
        try {
            const data = await promises_1.default.readFile(this.storagePath, "utf-8");
            const parsed = JSON.parse(data);
            Object.entries(parsed).forEach(([id, acc]) => {
                this.accounts.set(id, {
                    ...acc,
                    createdAt: new Date(acc.createdAt),
                    updatedAt: new Date(acc.updatedAt),
                    rateLimitedUntil: acc.rateLimitedUntil ? new Date(acc.rateLimitedUntil) : undefined
                });
            });
        }
        catch (e) { }
    }
    async saveAccounts() {
        await this.ensureDir();
        const data = JSON.stringify(Object.fromEntries(this.accounts), null, 2);
        await promises_1.default.writeFile(this.storagePath, data, "utf-8");
    }
    async addAccount(accountData) {
        const id = (0, uuid_1.v4)();
        const newAccount = {
            ...accountData,
            id,
            priority: this.accounts.size + 1,
            isRateLimited: false,
            quotaExhausted: false,
            createdAt: new Date(),
            updatedAt: new Date()
        };
        this.accounts.set(id, newAccount);
        await this.saveAccounts();
        return newAccount;
    }
    getNextAccount() {
        const active = Array.from(this.accounts.values())
            .filter(a => a.isActive && !a.isRateLimited && !a.quotaExhausted)
            .sort((a, b) => a.priority - b.priority);
        return active[0] || null;
    }
    removeAccount(id) {
        const deleted = this.accounts.delete(id);
        if (deleted)
            this.saveAccounts();
        return deleted;
    }
    listAccounts() {
        return Array.from(this.accounts.values()).sort((a, b) => a.priority - b.priority);
    }
    getActiveAccounts() {
        return this.listAccounts().filter(a => a.isActive && !a.isRateLimited && !a.quotaExhausted);
    }
}
exports.AccountManager = AccountManager;
//# sourceMappingURL=account-manager.js.map