<?php

// phpcs:disable WordPress.WP.AlternativeFunctions

namespace Waypoint\Agent\Dotenv;

class Manager {

	public static function find_dotenv(): ?string {
		$candidates = [
			dirname( ABSPATH, 2 ),
			dirname( ABSPATH, 3 ),
			dirname( ABSPATH ),
			ABSPATH,
		];
		foreach ( $candidates as $dir ) {
			$path = rtrim( $dir, '/\\' ) . '/.env';
			if ( is_readable( $path ) ) {
				return $path;
			}
		}
		return null;
	}

	public static function key_exists( string $path, string $key ): bool {
		$contents = @file_get_contents( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
		if ( ! is_string( $contents ) ) {
			return false;
		}
		return (bool) preg_match( '/^' . preg_quote( $key, '/' ) . '\s*=/m', $contents );
	}

	public static function get_key( string $path, string $key ): ?string {
		$contents = @file_get_contents( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
		if ( ! is_string( $contents ) ) {
			return null;
		}
		$pattern = '/^' . preg_quote( $key, '/' ) . '\s*=\s*(?:([\'"])(.*?)\1|(.*))$/m';
		if ( ! preg_match( $pattern, $contents, $m ) ) {
			return null;
		}
		$value = ( isset( $m[2] ) && '' !== $m[2] ) ? $m[2] : ( isset( $m[3] ) ? trim( $m[3] ) : '' );
		return strlen( $value ) >= 32 ? $value : null;
	}

	public static function append_key( string $path, string $key, string $value ): bool {
		if ( self::key_exists( $path, $key ) ) {
			return true;
		}
		$line   = PHP_EOL . $key . '=' . $value . PHP_EOL;
		$result = @file_put_contents( $path, $line, FILE_APPEND | LOCK_EX ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
		if ( false === $result ) {
			error_log( 'Waypoint Agent: failed to append ' . $key . ' to ' . $path );
			return false;
		}
		return true;
	}

	public static function set_key( string $path, string $key, string $value ): bool {
		$contents = @file_get_contents( $path ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
		if ( ! is_string( $contents ) ) {
			error_log( 'Waypoint Agent: cannot read .env at ' . $path );
			return false;
		}

		$escaped  = preg_quote( $key, '/' );
		$new_line = $key . '=' . $value;

		if ( preg_match( '/^' . $escaped . '\s*=/m', $contents ) ) {
			$new_contents = preg_replace( '/^' . $escaped . '\s*=.*$/m', $new_line, $contents );
		} else {
			$new_contents = rtrim( $contents ) . PHP_EOL . $new_line . PHP_EOL;
		}

		if ( null === $new_contents ) {
			error_log( 'Waypoint Agent: preg_replace failed while setting ' . $key );
			return false;
		}

		$tmp     = $path . '.tmp.' . getmypid();
		$written = @file_put_contents( $tmp, $new_contents, LOCK_EX ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
		if ( false === $written ) {
			error_log( 'Waypoint Agent: failed to write temp file ' . $tmp );
			return false;
		}

		if ( ! @rename( $tmp, $path ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors
			@unlink( $tmp ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
			error_log( 'Waypoint Agent: failed to rename temp .env — possible permissions issue' );
			return false;
		}

		return true;
	}
}
