"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;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.WorkspaceManager = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class WorkspaceManager {
    constructor(root = process.cwd()) {
        this.root = path.resolve(root);
    }
    async isMonorepo() {
        const pkgPath = path.join(this.root, "package.json");
        if (await fs.pathExists(pkgPath)) {
            const pkg = await fs.readJson(pkgPath);
            if (pkg.workspaces)
                return true;
        }
        if (await fs.pathExists(path.join(this.root, "pnpm-workspace.yaml")))
            return true;
        if (await fs.pathExists(path.join(this.root, "turbo.json")))
            return true;
        return false;
    }
    async getWorkspaces() {
        const workspaces = [];
        const pkgPath = path.join(this.root, "package.json");
        let patterns = [];
        if (await fs.pathExists(pkgPath)) {
            const pkg = await fs.readJson(pkgPath);
            if (pkg.workspaces) {
                patterns = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages || [];
            }
        }
        if (patterns.length === 0) {
            const pnpmWs = path.join(this.root, "pnpm-workspace.yaml");
            if (await fs.pathExists(pnpmWs)) {
                const content = await fs.readFile(pnpmWs, "utf8");
                const match = content.match(/packages:\s*\n((?:\s+-\s+.+\n?)*)/);
                if (match && match[1]) {
                    patterns = match[1]
                        .split("\n")
                        .map(l => l.replace(/^\s*-\s*['"]?/, "").replace(/['"]?\s*$/, ""))
                        .filter(Boolean);
                }
            }
        }
        for (const pattern of patterns) {
            const baseDir = pattern.replace(/\/?\*$/, "");
            const wsParentDir = path.join(this.root, baseDir);
            if (await fs.pathExists(wsParentDir)) {
                try {
                    const entries = await fs.readdir(wsParentDir, { withFileTypes: true });
                    for (const entry of entries) {
                        if (!entry.isDirectory())
                            continue;
                        const wsPath = path.join(baseDir, entry.name);
                        const absPath = path.join(this.root, wsPath);
                        const wsPkgPath = path.join(absPath, "package.json");
                        if (await fs.pathExists(wsPkgPath)) {
                            const wsPkg = await fs.readJson(wsPkgPath);
                            const wsDeps = { ...wsPkg.dependencies, ...wsPkg.devDependencies };
                            let type = "node";
                            if (wsDeps?.next)
                                type = "nextjs";
                            workspaces.push({
                                name: wsPkg.name || entry.name,
                                path: wsPath,
                                absolutePath: absPath,
                                type,
                                hasPackageJson: true,
                            });
                        }
                    }
                }
                catch (e) {
                    // Skip if directory reading fails
                }
            }
        }
        return workspaces;
    }
    /**
     * Identifies related packages in a monorepo for a given application path.
     * This helps in "Smart Scoping" by pulling in shared code.
     */
    async getRelatedPackages(appPath) {
        const absAppPath = path.resolve(appPath);
        const appPkgPath = path.join(absAppPath, "package.json");
        if (!(await fs.pathExists(appPkgPath)))
            return [];
        const appPkg = await fs.readJson(appPkgPath);
        const allDeps = new Set(Object.keys({
            ...appPkg.dependencies,
            ...appPkg.devDependencies,
            ...appPkg.peerDependencies
        }));
        const allWorkspaces = await this.getWorkspaces();
        return allWorkspaces.filter(ws => allDeps.has(ws.name) && ws.absolutePath !== absAppPath);
    }
    /**
     * Finds the root of the monorepo from any subdirectory
     */
    static async findRoot(startDir = process.cwd()) {
        let current = path.resolve(startDir);
        while (current !== path.parse(current).root) {
            if (await fs.pathExists(path.join(current, "pnpm-workspace.yaml")) ||
                await fs.pathExists(path.join(current, "turbo.json"))) {
                return current;
            }
            const pkgPath = path.join(current, "package.json");
            if (await fs.pathExists(pkgPath)) {
                const pkg = await fs.readJson(pkgPath);
                if (pkg.workspaces)
                    return current;
            }
            current = path.dirname(current);
        }
        return startDir;
    }
}
exports.WorkspaceManager = WorkspaceManager;
//# sourceMappingURL=workspace.js.map