Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

$RepoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
$KubernetesDir = Join-Path $RepoRoot "kubernetes"
$ApplicationManifestPath = Join-Path $KubernetesDir "argocd-application.yaml"
$NodePortManifestPath = Join-Path $KubernetesDir "argocd-server-nodeport.yaml"

$CurrentContext = ""
try {
  $CurrentContext = (kubectl config current-context 2>$null).Trim()
} catch {
  $CurrentContext = ""
}

if ([string]::IsNullOrWhiteSpace($CurrentContext)) {
  throw "kubectl current-context is not set. Configure a cluster first, then rerun deploy-kubernetes.ps1 (or use its -CreateKindClusterIfMissing option)."
}

try {
  kubectl cluster-info | Out-Null
} catch {
  throw "kubectl context '$CurrentContext' is not reachable. Select a running cluster and retry."
}

kubectl create namespace argocd --dry-run=client -o yaml | kubectl apply -f -
kubectl apply --server-side -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
kubectl apply -f $NodePortManifestPath
kubectl wait --for=condition=Established crd/applications.argoproj.io --timeout=120s

$RepoUrl = git -C $RepoRoot config --get remote.origin.url
if ([string]::IsNullOrWhiteSpace($RepoUrl)) {
  throw "Could not resolve git remote 'origin'. Set repoURL in kubernetes\\argocd-application.yaml manually."
}

$TargetRevision = git -C $RepoRoot rev-parse --abbrev-ref HEAD
if ([string]::IsNullOrWhiteSpace($TargetRevision)) {
  $TargetRevision = "main"
}

$ApplicationManifest = (Get-Content $ApplicationManifestPath -Raw).
  Replace("__REPO_URL__", $RepoUrl).
  Replace("__TARGET_REVISION__", $TargetRevision)

$ApplicationManifest | kubectl apply -f -

Write-Host ""
Write-Host "Argo CD installed and application registered."
Write-Host "UI (Kind on localhost): https://localhost:30080"
Write-Host "If NodePort is not reachable with Kind, use: kubectl port-forward svc/argocd-server -n argocd 8080:443"
