from __future__ import annotations
_A=True
import shutil,zipfile
from pathlib import Path
from admin import config
from admin.models import db
from admin.services.util import append_log
ARCHIVE_SKIP={'.venv','venv','__pycache__','logs'}
def archive_build(slug,app_dir,log_path,label):
	D=label;B=app_dir;E=config.RELEASES_ROOT/slug;E.mkdir(parents=_A,exist_ok=_A);C=E/f"{D}.zip";append_log(log_path,f"Archiving release {D} -> {C}")
	with zipfile.ZipFile(C,'w',compression=zipfile.ZIP_DEFLATED)as F:
		for A in B.rglob('*'):
			if not A.is_file():continue
			G=A.relative_to(B).parts
			if any(A in ARCHIVE_SKIP for A in G):continue
			if A.suffix=='.pyc':continue
			F.write(A,A.relative_to(B).as_posix())
	return C
def restore_archive(archive_path,app_dir,log_path):
	C=archive_path;A=app_dir;append_log(log_path,f"Restoring archive {C} -> {A}")
	if A.exists():
		for B in list(A.iterdir()):
			if B.name in{'venv','.venv'}:continue
			if B.is_dir():shutil.rmtree(B,ignore_errors=_A)
			else:B.unlink(missing_ok=_A)
	else:A.mkdir(parents=_A,exist_ok=_A)
	with zipfile.ZipFile(C,'r')as D:D.extractall(A)
def prune_releases(slug,log_path):
	C=max(1,config.MAX_RELEASES_KEPT);D=db.list_old_releases(slug,keep=C)
	for A in D:
		if A.is_current:continue
		B=Path(A.archive_path)
		if B.exists():B.unlink(missing_ok=_A);append_log(log_path,f"Pruned old release archive {B.name}")
		db.delete_release_row(A.id)
