import 'dotenv/config';
import { z } from 'zod';

const envSchema = z.object({
  // Agent server
  AGENT_PORT: z.coerce.number().default(7443),
  AGENT_LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),

  // TLS certificates (required once approved)
  AGENT_CERT_PATH: z.string().default('/etc/ccp-agent/agent.pem'),
  AGENT_KEY_PATH: z.string().default('/etc/ccp-agent/agent.key'),
  AGENT_CA_CERT_PATH: z.string().default('/etc/ccp-agent/ca.pem'),

  // Allowed CCP fingerprints (comma-separated SHA-256 hex)
  ALLOWED_CCP_FINGERPRINTS: z.string().default(''),

  // Data directory (registry.json lives here)
  AGENT_DATA_DIR: z.string().default('/var/lib/ccp-agent'),

  // Phone-home registration (set during initial setup, cleared after approval)
  CCP_URL: z.string().default(''),
  CCP_INVITE_CODE: z.string().default(''),
  CCP_AGENT_URL: z.string().default(''), // How CCP can reach this agent

  // Instance info (for phone-home registration)
  INSTANCE_SLUG: z.string().default(''),
  INSTANCE_DOMAIN: z.string().default(''),
  INSTANCE_BASE_PATH: z.string().default(''),
  COMPOSE_PROJECT: z.string().default(''),
});

function validateEnv() {
  const result = envSchema.safeParse(process.env);
  if (!result.success) {
    console.error('Invalid environment variables:');
    for (const [key, errors] of Object.entries(result.error.flatten().fieldErrors)) {
      console.error(`  ${key}: ${errors?.join(', ')}`);
    }
    process.exit(1);
  }
  return result.data;
}

export const env = validateEnv();
