from __future__ import annotations
import sys
from pathlib import Path
from admin import config
from admin.services.util import append_log,run_command
class VenvError(Exception):0
def python_bin(venv_dir):
	A=venv_dir
	if sys.platform=='win32':return A/'Scripts'/'python.exe'
	return A/'bin'/'python'
def ensure_venv(app_dir,log_path,requirements_rel='requirements.txt'):
	M='venv';J=app_dir;I='install';G=requirements_rel;F='pip';E='-m';B=log_path;H=J/M;K=config.PYTHON_EXE
	if not H.exists():
		append_log(B,f"Creating venv with {K}");C,A=run_command([K,E,M,str(H)]);append_log(B,A)
		if C!=0:raise VenvError(f"venv creation failed:\n{A}")
	D=python_bin(H)
	if not D.exists():raise VenvError(f"venv python missing: {D}")
	append_log(B,'Upgrading pip');C,A=run_command([str(D),E,F,I,'--upgrade',F]);append_log(B,A)
	if C!=0:raise VenvError(f"pip upgrade failed:\n{A}")
	L=J/G
	if L.is_file():
		append_log(B,f"Installing requirements from {G}");C,A=run_command([str(D),E,F,I,'-r',str(L)],cwd=J,timeout=900);append_log(B,A)
		if C!=0:raise VenvError(f"pip install -r {G} failed:\n{A}")
	else:
		append_log(B,f"No {G} found; installing Flask only");C,A=run_command([str(D),E,F,I,'Flask']);append_log(B,A)
		if C!=0:raise VenvError(f"pip install Flask failed:\n{A}")
	append_log(B,'Ensuring Waitress is installed');C,A=run_command([str(D),E,F,I,'Waitress']);append_log(B,A)
	if C!=0:raise VenvError(f"pip install Waitress failed:\n{A}")
	return H
