import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, statSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { FooterComponent } from "@sheason/pi-coding-agent";
function toSessionEntries(view) {
    return (view.session?.items ?? []).filter((item) => item.type === "message").map((item) => item);
}
function resolveModelFromView(view) {
    if (view.session?.model) {
        return {
            id: view.session.model.modelId,
            provider: view.session.model.provider,
            contextWindow: view.footer.contextWindow ?? 0,
            reasoning: (view.session.availableModels ?? []).some((model) => model.provider === view.session?.model?.provider &&
                model.modelId === view.session?.model?.modelId &&
                model.reasoning),
        };
    }
    const label = view.footer.modelLabel;
    const slashIdx = label.lastIndexOf("/");
    return slashIdx > 0
        ? {
            id: label.slice(slashIdx + 1),
            provider: label.slice(0, slashIdx),
            contextWindow: view.footer.contextWindow ?? 0,
        }
        : { id: label, provider: "", contextWindow: view.footer.contextWindow ?? 0 };
}
export class RemoteSessionAdapter {
    view;
    state = { thinkingLevel: "off" };
    session;
    constructor() {
        const state = this.state;
        this.session = {
            get state() {
                return state;
            },
            sessionManager: {
                getCwd: () => this.view?.footer.cwd ?? "",
                getEntries: () => (this.view ? toSessionEntries(this.view) : []),
                getSessionName: () => this.view?.session?.sessionName,
            },
            modelRegistry: {
                isUsingOAuth: () => false,
            },
            getContextUsage: () => this.view?.footer.contextUsage,
        };
    }
    setView(view) {
        this.view = view;
        this.state.model = resolveModelFromView(view);
        this.state.thinkingLevel = view.session?.thinkingLevel ?? "off";
        return this.session;
    }
}
function findGitPaths(cwd) {
    let dir = cwd;
    while (true) {
        const gitPath = join(dir, ".git");
        if (existsSync(gitPath)) {
            try {
                const stat = statSync(gitPath);
                if (stat.isFile()) {
                    const content = readFileSync(gitPath, "utf8").trim();
                    if (content.startsWith("gitdir: ")) {
                        const gitDir = resolve(dir, content.slice(8).trim());
                        const headPath = join(gitDir, "HEAD");
                        if (!existsSync(headPath))
                            return null;
                        const commonDirPath = join(gitDir, "commondir");
                        const commonGitDir = existsSync(commonDirPath)
                            ? resolve(gitDir, readFileSync(commonDirPath, "utf8").trim())
                            : gitDir;
                        return { repoDir: dir, commonGitDir, headPath };
                    }
                }
                else if (stat.isDirectory()) {
                    const headPath = join(gitPath, "HEAD");
                    if (!existsSync(headPath))
                        return null;
                    return { repoDir: dir, commonGitDir: gitPath, headPath };
                }
            }
            catch {
                return null;
            }
        }
        const parent = dirname(dir);
        if (parent === dir)
            return null;
        dir = parent;
    }
}
function resolveBranchWithGitSync(repoDir) {
    const result = spawnSync("git", ["--no-optional-locks", "symbolic-ref", "--quiet", "--short", "HEAD"], {
        cwd: repoDir,
        encoding: "utf8",
        stdio: ["ignore", "pipe", "ignore"],
    });
    const branch = result.status === 0 ? result.stdout.trim() : "";
    return branch || null;
}
export class RemoteFooterDataProvider {
    availableProviderCount = 0;
    extensionStatuses = new Map();
    cwd;
    getGitBranch() {
        if (!this.cwd)
            return null;
        try {
            const gitPaths = findGitPaths(this.cwd);
            if (!gitPaths)
                return null;
            const content = readFileSync(gitPaths.headPath, "utf8").trim();
            if (content.startsWith("ref: refs/heads/")) {
                const branch = content.slice(16);
                return branch === ".invalid" ? (resolveBranchWithGitSync(gitPaths.repoDir) ?? "detached") : branch;
            }
            return "detached";
        }
        catch {
            return null;
        }
    }
    getExtensionStatuses() {
        return this.extensionStatuses;
    }
    getAvailableProviderCount() {
        return this.availableProviderCount;
    }
    onBranchChange() {
        return () => { };
    }
    setCwd(cwd) {
        this.cwd = cwd;
    }
    setAvailableProviderCount(count) {
        this.availableProviderCount = count;
    }
    setExtensionStatus(key, text) {
        if (text === undefined)
            this.extensionStatuses.delete(key);
        else
            this.extensionStatuses.set(key, text);
    }
}
export function createRemoteFooterComponent() {
    const session = new RemoteSessionAdapter();
    const footerData = new RemoteFooterDataProvider();
    return {
        footer: new FooterComponent(session.setView({
            connection: { state: "idle" },
            peers: [],
            footer: {
                cwd: "",
                modelLabel: "no-model",
                queueSummary: "queued 0",
                pendingToolCount: 0,
                peerCount: 0,
                isRunning: false,
                peerId: "peer",
                boundAgentId: "root",
            },
            status: { diagnostics: [] },
            commands: [],
        }), footerData),
        session,
        footerData,
    };
}
//# sourceMappingURL=remote-footer-adapter.js.map