import { getPersonaPrefix } from "../personas.js";
import { AUTH_TYPES_PROMPT_LIST } from "../../utils/workspaceAuth.js";
export const INIT_WORKSPACE_INSTRUCTIONS = `${getPersonaPrefix()}Your task is to scan this repository, discover ALL services, and call the skyramp_init_workspace tool with the discovered services array and the scanToken.

After scanning the workspace, before calling the skyramp_init_workspace tool, you MUST:
1. Output a <thinking> block to justify the reasoning behind each field mapping for every discovered service. Follow the scanning sections first, then field definitions, then verification.
2. Then output a Discovery Summary with the exact services array you will pass to the tool:
\`\`\`json
[
  {
    "serviceName": "<name>",
    "language": "<language>",
    "framework": "<framework>",
    "testDirectory": "<path>",
    "api": { "schemaPath": "<path-or-url>", "baseUrl": "<url>", "authType": "<type>", "authHeader": "<header>" },
    "runtimeDetails": { "runtime": "<runtime>", "serverStartCommand": "<command>", "dockerNetwork": "<network>" }
  }
]
\`\`\`

### List all top-level directories
<list_directories>
Run a directory listing of the workspace root. Every top-level directory is a potential service. Common layouts:
| Layout | Example dirs | Expect |
|--------|-------------|--------|
| Monorepo | apps/web, apps/api, packages/shared | 1 service per app |
| Microservices | services/auth, services/orders | 1 service per service dir |
| Single service | src/, lib/ | 1 service (the root) |

If the repo is a monorepo, check for workspace manifests BEFORE scanning individual directories:
1. JavaScript/TypeScript monorepos:
   - If pnpm-workspace.yaml exists, read the packages array to find all package directories (for example, ["apps/*", "packages/*"]).
   - If turbo.json exists, read the root package.json workspaces field to enumerate all packages.
   - If lerna.json exists, read the packages array in lerna.json (for example, ["packages/*"]).
   - If the root package.json has a "workspaces" field, use the glob patterns to identify all packages.
   - If nx.json exists, scan the projects in nx.json or project.json files in subdirectories.
2. Java monorepos:
   - If a parent pom.xml has a <modules> section, each listed module is a separate service (Maven multi-module project).
   - If settings.gradle or settings.gradle.kts has include statements, each included project is a separate service (Gradle multi-project).
3. Python monorepos:
   - If a pyproject.toml has a [tool.poetry.packages] or [tool.setuptools.packages] section with multiple paths, each is a potential service.
   - If multiple directories each contain their own pyproject.toml or requirements.txt, treat each as an independent service.
When any of these exist, use the workspace manifest to enumerate ALL packages and apps. Each package with its own server entry point, API routes, or UI framework is a separate service. Do NOT skip frontend packages. A Next.js app, React SPA, or Vue app in the monorepo is a service.
</list_directories>

### Inspect every candidate directory
<inspect_directories>
For each top-level directory, check for service indicator files.

Language indicators (presence of any means an independent service):
1. package.json indicates typescript or javascript
2. requirements.txt, pyproject.toml, or Pipfile indicates python
3. pom.xml or build.gradle indicates java

Test framework (look inside the service directory):
1. playwright.config.* indicates playwright
2. pytest.ini, conftest.py, or pyproject.toml [tool.pytest] indicates pytest
3. junit in pom.xml indicates junit

API schemas (look inside the service directory and check known framework defaults):
1. openapi.json/yaml or swagger.json/yaml provides the schema file path
2. FastAPI projects serve the schema at http://localhost:{port}/openapi.json
3. Express with swagger-ui serves at http://localhost:{port}/api-docs
4. Spring Boot serves at http://localhost:{port}/v3/api-docs
</inspect_directories>

### Check root-level runtime config
<runtime_config>
Inspect the repo root (and subdirectories like .devcontainer/) for shared runtime configuration:
1. CLAUDE.md or AGENTS.md: if either file exists at the repo root, check it for dev/test/CI setup instructions including how to start services, required environment variables, and runtime configuration.
2. Docker Compose files: scan for ALL compose files including docker-compose.yml, docker-compose.yaml, docker-compose.*.yml (such as docker-compose.testbot.yml or docker-compose.dev.yml), compose.yml, and compose.*.yaml in the repo root and subdirectories. Distinguish between application compose files and infrastructure-only compose files. Infrastructure compose files contain only supporting services like databases, Redis, Minio, mail servers, or message queues and do NOT run the application itself. Application compose files contain the actual application services that build from the repo source code (look for "build:" directives pointing to the repo, or services that map to discovered application directories). Only use application compose files for determining runtime and serverStartCommand. When a non-default compose file is found, the serverStartCommand must reference it explicitly (such as "docker compose -f docker-compose.testbot.yml up -d <service-name>"). Docker Compose ALWAYS prefixes the network name with the project name. If compose has "networks: { my-net: ... }", the actual network name is "<project-name>_my-net". If there is no explicit networks section, the default network is "<project-name>_default". The project name is the basename of the working directory where docker compose runs.
3. Makefile: extract start and dev targets.
4. Root package.json scripts: extract workspace-level commands.
</runtime_config>

### Build the complete services array
<build_services>
Create one service entry per deployable unit. You MUST include every backend/API service (Python, Java, Go, Node.js) and every frontend service (React, Vue, Angular, Next.js). Set runtime fields from docker-compose.yml if present.
</build_services>

### Basic fields
<basic_fields>
1. serviceName (required): A unique identifier for the service. Use the format <repoName>-<serviceDirName>-<frontend or backend> for consistency. For example: directus-api-backend, directus-app-frontend. If the directory name already ends with "backend" or "frontend", do not duplicate the suffix (use "demoshop-fullstack-backend" not "demoshop-fullstack-backend-backend"). For single-service repos where the service directory is the root, omit the directory portion such as onlineBoutique-frontend.
2. language (required): One of python, typescript, javascript, or java. Detect from package.json (typescript or javascript), requirements.txt or pyproject.toml (python), or pom.xml or build.gradle (java).
3. framework (required): One of playwright, pytest, robot, or junit. Detect from pytest.ini, playwright.config, jest.config, or junit in pom.xml. The framework MUST match the language: python uses pytest or robot, typescript or javascript uses playwright, and java uses junit.
4. testDirectory (required): A stable path relative to the repo root where generated tests for this service will be placed. For each service, use the test directory configured by that service's test framework when one is discoverable:
   - Playwright: Read playwright.config.ts (or .js/.mjs) and extract the testDir value.
   - pytest: Read pytest.ini, pyproject.toml [tool.pytest.ini_options], or setup.cfg [tool:pytest] for testpaths.
   - JUnit: Usually src/test/java. Check pom.xml or build.gradle for custom test source directories.
   If no framework-configured test directory is available, use the Skyramp deterministic fallback:
   - Single service: set testDirectory to tests/skyramp.
   - Multiple services or monorepos: set testDirectory to tests/skyramp/<serviceDirName>, where <serviceDirName> is the service directory name with path separators and whitespace replaced by hyphens.
   Framework config takes precedence. Use the Skyramp deterministic fallback only when no framework-configured test directory is available.
</basic_fields>

### API fields
<api_fields>
1. api.schemaPath: Path or URL to an OpenAPI or Swagger schema. Search for openapi.json, openapi.yaml, swagger.json, or swagger.yaml files. Framework defaults are: FastAPI serves /openapi.json, Express serves /api-docs, and Spring serves /v3/api-docs. For locally-run services, use a localhost URL. For cloud or externally hosted services (such as Salesforce, Vercel, or Cloudflare), use the actual deployment URL found in config or documentation.
2. api.baseUrl (required): The base URL where the service is reachable, such as "http://localhost:3000" or "https://api.example.com". Derive from docker-compose ports, app config, README, or environment variables. Use localhost for services run locally and the actual deployment URL for cloud or externally hosted services. NEVER fabricate a URL. Only use URLs found in config files, README, or environment variables.
3. api.authType (required): The authentication type. Valid values are: ${AUTH_TYPES_PROMPT_LIST}
   Detect by checking in the following order (language-agnostic, apply whichever signals match):
   a. Dependencies and packages (package.json, requirements.txt, go.mod, Gemfile, composer.json, pom.xml, build.gradle):
      - jsonwebtoken, passport-jwt, @nestjs/jwt, jose, fastapi[security], PyJWT, python-jose, github.com/golang-jwt/jwt, jjwt, or spring-security-oauth2 indicates bearer. Spring exception: if spring-security is present but the security config uses HttpSecurity.formLogin() or sessionManagement() without a JwtDecoder bean, the actual auth is session cookies so use cookie. Check the SecurityConfig or WebSecurityConfigurerAdapter class before assigning bearer to any Spring service.
      - passport-http or Spring basic auth indicates basic.
      - passport-oauth2, openid-client, doorkeeper, keycloak-connect, spring-security-oauth2-resource-server, or github.com/coreos/go-oidc indicates oauth.
      - rest_framework with TokenAuthentication or djangorestframework-simplejwt (Token scheme) indicates token.
      - express-session, cookie-session, iron-session, next-auth, gorilla/sessions, or laravel/session indicates cookie.
      - laravel/sanctum or laravel/passport on API routes indicates bearer; on frontend web routes indicates cookie.
   b. Environment variables (.env, docker-compose, README):
      - JWT_SECRET, ACCESS_TOKEN_SECRET, FIREBASE_SECRET, or SUPABASE_JWT_SECRET indicates bearer.
      - API_KEY, X_API_KEY, ADMIN_KEY, or SERVICE_KEY (used as header value, not JWT signing) indicates apiKey.
      - CLIENT_ID paired with CLIENT_SECRET, OAUTH_CLIENT_*, or OIDC_* indicates oauth.
      - SESSION_SECRET, COOKIE_SECRET, or NEXTAUTH_SECRET indicates cookie.
   c. Source code and middleware patterns (auth, middleware, or security config files):
      - Node/Express: req.headers.authorization split "Bearer" indicates bearer. "Authorization: Token" indicates token. Custom header check indicates apiKey. Session or cookie middleware indicates cookie.
      - FastAPI/Starlette: HTTPBearer, OAuth2PasswordBearer, or Depends(get_current_user) indicates bearer. SessionMiddleware indicates cookie.
      - Django/DRF: TokenAuthentication indicates token. JWTAuthentication indicates bearer. SessionAuthentication indicates cookie.
      - Spring: JwtDecoder or JwtAuthenticationFilter indicates bearer. HttpSecurity.formLogin() with sessions indicates cookie.
      - Go: ParseWithClaims or GetHeader("Authorization") indicates bearer. gorilla/sessions indicates cookie.
      - Rails: authenticate_or_request_with_http_token indicates bearer. before_action :authenticate_user! (Devise) indicates cookie.
      - Laravel: auth:sanctum on API indicates bearer. middleware("auth") on web indicates cookie.
      - Rust/Axum: Authorization<Bearer> extraction indicates bearer.
   d. Query-parameter auth: Some APIs pass credentials as a URL query param rather than a header (such as ?key=<key>, ?api_key=<key>, or ?access_token=<token>). Signals include source code reading credentials from req.query.key, request.query_params["api_key"], or @RequestParam("token"), and API docs or README showing auth examples like /endpoint?key=<your-key>.
   e. Fallback: For frontend or UI services, use none. For backend APIs with no header-based auth signals, use bearer.
4. api.authHeader: The exact HTTP header name carrying the credential.
   - For bearer, basic, oauth, or token: always "Authorization" (inferred automatically, so you may omit it).
   - For cookie or session: always "Cookie" (also inferred automatically).
   - For apiKey: this is required. Set to the actual custom header name such as "X-API-Key" or "X-Admin-Key".
   - For none: set authHeader to "".
5. api.authScheme: The Authorization header prefix (the word before the token). Standard types derive this automatically: bearer uses "Bearer", token uses "Token", and basic uses "Basic". Set explicitly only for custom or non-standard schemes (for example, Hawk uses "Hawk" and Digest uses "Digest"). Omit for cookie, session, or apiKey since they do not use the Authorization header.
</api_fields>

### Runtime fields
<runtime_fields>
1. runtimeDetails.runtime (required): One of local, docker, or k8s. Detect per service:
   - If the service is listed in an application docker compose file (one that builds or runs the application, not infrastructure-only files containing only databases, caches, or queues) or has a Dockerfile as its intended run method, use "docker".
   - If k8s manifests exist (charts/, k8s/, deploy/), use "k8s".
   - If the service has no Docker or k8s configuration and is run directly via a language runtime (npm, python, java, etc.), use "local".
   A repo may have MIXED runtimes. A backend in docker-compose.yml uses "docker" while a frontend run with pnpm or npm locally uses "local". Include ALL services regardless of runtime.
   If the frontend is bundled inside the API Docker container (no separate frontend service in the compose file), both frontend and backend services should use runtime "docker", share the same baseUrl (the container's exposed URL), and use the same serverStartCommand since they run in the same container.
2. runtimeDetails.serverStartCommand: The command to start or deploy the service. It MUST match the runtime:
   - For "docker" runtime: Use a Docker command such as "docker compose up -d <service-name>" for the default docker-compose.yml, or "docker compose -f <compose-file> up -d <service-name>" when using a non-default compose file. This is always derivable from the application docker compose file and service name.
   - For "k8s" runtime: Use a deploy command such as "kubectl apply -f deploy/", "helm install myrelease .", or "skaffold run". This is always derivable from the manifests or charts present in the repo.
   - For "local" runtime: Use an application command such as "uvicorn main:app", "npm run dev", or "java -jar app.jar". Derive from Makefile, package.json scripts, or README. If no start command is discoverable, omit this field entirely.
   NEVER mix runtime types with incompatible commands (for example, using "uvicorn" with runtime "docker" will cause errors). For "local" runtime, NEVER fabricate a command. Only use commands found in Makefile, package.json scripts, or README.
3. runtimeDetails.dockerNetwork: Docker network name. ONLY set when runtime is "docker". NEVER set for "local" or "k8s".
4. runtimeDetails.k8sNamespace: Kubernetes namespace. ONLY set when runtime is "k8s". NEVER set for "local" or "docker".
5. runtimeDetails.k8sContext: Kubernetes context. ONLY set when runtime is "k8s". NEVER set for "local" or "docker".
</runtime_fields>

### Verification
<verification>
Before calling skyramp_init_workspace, confirm all of the following:
1. Always scan the repo and find services. A repo should have at least one service.
2. ALL services are included, both backend and frontend. The workspace config is a complete registry of the entire repo, not just the service relevant to your current task. A fullstack or monorepo MUST have multiple services. If you found only one, re-scan every top-level directory before proceeding.
3. Services NOT in docker-compose.yml (such as a frontend run with pnpm or npm locally) MUST still be included with runtime "local".
4. Every service has api.baseUrl set to a valid, discoverable URL. Use localhost for local services or the actual deployment URL for cloud or external services. Never fabricate a URL.
5. Every service with authType apiKey has authHeader explicitly set to the actual custom header name (such as "X-API-Key" or "X-Admin-Key"). If you cannot find the header name in the source code, env vars, or README, do NOT use authType apiKey. Use authType none instead and add a YAML comment explaining auth is unresolved.
6. framework matches language (python uses pytest or robot, typescript or javascript uses playwright, java uses junit).
7. testDirectory follows the stable resolution rules above: framework config file when present (Playwright testDir in playwright.config.ts, pytest testpaths in pytest.ini or pyproject.toml, JUnit test source dir in pom.xml or build.gradle); otherwise the deterministic default (tests/skyramp for a single service, tests/skyramp/<serviceDirName> for multiple services).
8. If serverStartCommand is provided, it matches the runtime.
9. For services in docker-compose.yml: runtime MUST be "docker" and the command MUST be a docker command such as "docker compose up -d <service-name>". Always include it since it is derivable from the service name.
10. NEVER use application-level commands (uvicorn, npm, node, python, java, etc.) with runtime "docker".
11. For "local" runtime: if no start command is discoverable from Makefile, package.json scripts, or README, omit serverStartCommand rather than guessing.
12. dockerNetwork is set only when runtime is "docker".
13. k8sNamespace and k8sContext are set only when runtime is "k8s".
14. If force-recreating a workspace.yml due to a schema validation error, correct the schema error but keep any valid system-under-test setup (serviceName, baseUrl, auth config, runtime details) as it is.
</verification>

Once verified, call skyramp_init_workspace with:
- workspacePath: the repository root path
- services: the array built above
- scanToken: the token returned by the first call to skyramp_init_scan
- force: defaults to false. Set to true only if the user explicitly asks to overwrite an existing .skyramp/workspace.yml, or if the existing file must be regenerated due to a validation failure such as a schema mismatch, unknown fields, or a parse error.`;
