"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const prompts_1 = __importDefault(require("prompts"));
const hostedApiClient_1 = require("../utils/hostedApiClient");
const api_1 = require("../config/api");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class AuthCommand {
    constructor() {
        this.hostedApi = new hostedApiClient_1.HostedApiClient();
        this.configPath = path.join(process.cwd(), ".mycontext", "auth.json");
    }
    async execute(options) {
        try {
            if (options.login) {
                await this.login();
            }
            else if (options.logout) {
                await this.logout();
            }
            else if (options.status) {
                await this.status();
            }
            else if (options.register) {
                await this.register();
            }
            else {
                // Interactive mode
                await this.interactiveAuth();
            }
        }
        catch (error) {
            console.error(chalk_1.default.red(`❌ Auth error: ${error instanceof Error ? error.message : "Unknown error"}`));
            process.exit(1);
        }
    }
    async interactiveAuth() {
        console.log(chalk_1.default.blue("\n🔐 MyContext Authentication"));
        console.log(chalk_1.default.gray("Choose an option:"));
        const response = await (0, prompts_1.default)({
            type: "select",
            name: "action",
            message: "What would you like to do?",
            choices: [
                { title: "Login to MyContext AI", value: "login" },
                { title: "Register new account", value: "register" },
                { title: "Check auth status", value: "status" },
                { title: "Logout", value: "logout" },
            ],
        });
        if (!response.action) {
            console.log(chalk_1.default.yellow("Operation cancelled."));
            return;
        }
        switch (response.action) {
            case "login":
                await this.login();
                break;
            case "register":
                await this.register();
                break;
            case "status":
                await this.status();
                break;
            case "logout":
                await this.logout();
                break;
        }
    }
    async login() {
        console.log(chalk_1.default.blue("\n🔑 Login to MyContext AI"));
        // Check if already logged in
        const currentAuth = await this.getStoredAuth();
        if (currentAuth?.token) {
            const isValid = await this.validateToken(currentAuth.token);
            if (isValid) {
                console.log(chalk_1.default.green(`✅ Already logged in as ${currentAuth.email}`));
                return;
            }
        }
        // Open browser for OAuth flow
        console.log(chalk_1.default.yellow("Opening browser for authentication..."));
        try {
            const loginUrl = (0, api_1.getAuthUrl)("/login");
            // await open(loginUrl);
            console.log(chalk_1.default.yellow("Please open this URL in your browser:"));
            console.log(chalk_1.default.blue(loginUrl));
        }
        catch (error) {
            console.log(chalk_1.default.yellow("Please open this URL in your browser:"));
            console.log(chalk_1.default.blue("https://mycontext.fbien.com/auth/login"));
        }
        // Get token from user
        const response = await (0, prompts_1.default)({
            type: "password",
            name: "token",
            message: "Enter your API token from the website:",
            validate: (value) => value.length > 0 || "Token is required",
        });
        if (!response.token) {
            console.log(chalk_1.default.yellow("Login cancelled."));
            return;
        }
        // Validate token
        const isValid = await this.validateToken(response.token);
        if (!isValid) {
            console.log(chalk_1.default.red("❌ Invalid token. Please check and try again."));
            return;
        }
        // Get user info
        const userInfo = await this.getUserInfo(response.token);
        if (!userInfo) {
            console.log(chalk_1.default.red("❌ Failed to get user information."));
            return;
        }
        // Store auth
        await this.storeAuth({
            token: response.token,
            email: userInfo.email,
            userId: userInfo.id,
            expiresAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30 days
        });
        console.log(chalk_1.default.green(`✅ Successfully logged in as ${userInfo.email}`));
        console.log(chalk_1.default.gray(`   Plan: ${userInfo.subscriptionStatus || "Free"}`));
        console.log(chalk_1.default.gray(`   Credits: ${userInfo.creditsRemaining || "Unlimited"}`));
    }
    async register() {
        console.log(chalk_1.default.blue("\n📝 Register for MyContext AI"));
        // Open browser for registration
        console.log(chalk_1.default.yellow("Opening browser for registration..."));
        try {
            const registerUrl = (0, api_1.getAuthUrl)("/register");
            // await open(registerUrl);
            console.log(chalk_1.default.yellow("Please open this URL in your browser:"));
            console.log(chalk_1.default.blue(registerUrl));
        }
        catch (error) {
            console.log(chalk_1.default.yellow("Please open this URL in your browser:"));
            console.log(chalk_1.default.blue("https://mycontext.fbien.com/auth/register"));
        }
        console.log(chalk_1.default.gray("\nAfter registering, come back and run:"));
        console.log(chalk_1.default.blue("mycontext auth login"));
    }
    async status() {
        console.log(chalk_1.default.blue("\n📊 Authentication Status"));
        const auth = await this.getStoredAuth();
        if (!auth?.token) {
            console.log(chalk_1.default.yellow("❌ Not logged in"));
            console.log(chalk_1.default.gray("Run 'mycontext auth login' to authenticate"));
            return;
        }
        // Validate token
        const isValid = await this.validateToken(auth.token);
        if (!isValid) {
            console.log(chalk_1.default.red("❌ Token expired or invalid"));
            console.log(chalk_1.default.gray("Run 'mycontext auth login' to re-authenticate"));
            return;
        }
        // Get fresh user info
        const userInfo = await this.getUserInfo(auth.token);
        if (!userInfo) {
            console.log(chalk_1.default.red("❌ Failed to get user information"));
            return;
        }
        console.log(chalk_1.default.green("✅ Authenticated"));
        console.log(chalk_1.default.gray(`   Email: ${userInfo.email}`));
        console.log(chalk_1.default.gray(`   Plan: ${userInfo.subscriptionStatus || "Free"}`));
        console.log(chalk_1.default.gray(`   Credits: ${userInfo.creditsRemaining || "Unlimited"}`));
        console.log(chalk_1.default.gray(`   Token expires: ${auth.expiresAt}`));
    }
    async logout() {
        console.log(chalk_1.default.blue("\n🚪 Logging out..."));
        const auth = await this.getStoredAuth();
        if (!auth?.token) {
            console.log(chalk_1.default.yellow("❌ Not logged in"));
            return;
        }
        // Clear stored auth
        await this.clearAuth();
        console.log(chalk_1.default.green("✅ Successfully logged out"));
    }
    async validateToken(token) {
        try {
            const response = await fetch((0, api_1.getApiUrl)("/auth/status"), {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            });
            return response.ok;
        }
        catch (error) {
            return false;
        }
    }
    async getUserInfo(token) {
        try {
            const response = await fetch((0, api_1.getApiUrl)("/auth/status"), {
                headers: {
                    Authorization: `Bearer ${token}`,
                },
            });
            if (!response.ok) {
                return null;
            }
            const data = (await response.json());
            return data.user;
        }
        catch (error) {
            return null;
        }
    }
    async getStoredAuth() {
        try {
            if (await fs.pathExists(this.configPath)) {
                return await fs.readJson(this.configPath);
            }
        }
        catch (error) {
            // Ignore errors
        }
        return null;
    }
    async storeAuth(auth) {
        await fs.ensureDir(path.dirname(this.configPath));
        await fs.writeJson(this.configPath, auth, { spaces: 2 });
    }
    async clearAuth() {
        try {
            if (await fs.pathExists(this.configPath)) {
                await fs.remove(this.configPath);
            }
        }
        catch (error) {
            // Ignore errors
        }
    }
}
exports.AuthCommand = AuthCommand;
//# sourceMappingURL=auth.js.map