package parser

import (
	"fmt"
	"path/filepath"
	"strings"
)

// WorkspaceDir returns the local clone directory for a repository ID.
// Matches repo-sync convention:
//   legacy "ad/foo"              → "{workspace}/ad__foo"
//   gateway "github:org/repo"    → "{workspace}/github__org__repo"
func WorkspaceDir(workspacePath, repoID string) (string, error) {
	repoID = strings.TrimSpace(repoID)
	if repoID == "" {
		return "", fmt.Errorf("repo_id is required")
	}
	if strings.TrimSpace(workspacePath) == "" {
		return "", fmt.Errorf("workspace path is required")
	}

	dirName := strings.ReplaceAll(repoID, "/", "__")
	dirName = strings.ReplaceAll(dirName, ":", "__")
	return filepath.Join(workspacePath, dirName), nil
}

// ResolveSourcePath returns the absolute path to a source file under the workspace.
func ResolveSourcePath(workspacePath, repoID, filePath string) (string, error) {
	repoDir, err := WorkspaceDir(workspacePath, repoID)
	if err != nil {
		return "", err
	}

	filePath = strings.TrimSpace(filePath)
	if filePath == "" {
		return "", fmt.Errorf("file_path is required")
	}

	return filepath.Join(repoDir, filepath.FromSlash(filePath)), nil
}
