import { useSessionStore } from '@/stores/useSessionStore';
import { useDirectoryStore } from '@/stores/useDirectoryStore';
import type { Session } from '@opencode-ai/sdk/v2';

/**
 * Hook that resolves the effective working directory for tabs (Git, Diff, Files, Terminal).
 * 
 * Priority order:
 * 1. Worktree metadata path (for worktree sessions)
 * 2. Session directory (for active sessions)
 * 3. Draft session directoryOverride (when creating a new session)
 * 4. Fallback directory from DirectoryStore
 * 
 * This ensures that tabs show content from the correct project directory
 * even when a draft session is being created.
 */
export const useEffectiveDirectory = (): string | undefined => {
    const {
        currentSessionId,
        sessions,
        worktreeMetadata: worktreeMap,
        newSessionDraft,
    } = useSessionStore();
    const { currentDirectory: fallbackDirectory } = useDirectoryStore();

    // If we have an active session, use its directory
    if (currentSessionId) {
        const worktreeMetadata = worktreeMap.get(currentSessionId);
        if (worktreeMetadata?.path) {
            return worktreeMetadata.path;
        }

        const currentSession = sessions.find((session) => session.id === currentSessionId);
        type SessionWithDirectory = Session & { directory?: string };
        const sessionDirectory = (currentSession as SessionWithDirectory | undefined)?.directory;
        if (sessionDirectory) {
            return sessionDirectory;
        }
    }

    // If a draft session is open, use its directoryOverride
    if (newSessionDraft?.open && newSessionDraft.directoryOverride) {
        return newSessionDraft.directoryOverride;
    }

    // Fall back to the global directory
    return fallbackDirectory ?? undefined;
};
