from __future__ import annotations
import os,shutil
from pathlib import Path
from admin.services.util import append_log
IGNORE_NAMES={'.git','.svn','.hg','.venv','venv','__pycache__','.idea','.vscode','.DS_Store','node_modules','logs','web.config'}
class FolderIngestError(Exception):0
def validate_project_folder(source):
	A=source;A=Path(str(A).strip().strip('"')).expanduser()
	if not str(A):raise FolderIngestError('Project folder path is required.')
	try:A=A.resolve()
	except OSError as B:raise FolderIngestError(f"Cannot resolve path: {B}")from B
	if not A.exists():raise FolderIngestError(f"Folder not found: {A}")
	if not A.is_dir():raise FolderIngestError(f"Path is not a folder: {A}")
	return A
def sync_folder(source,dest,log_path):
	F='.pyc';D=log_path;B=source;B=validate_project_folder(B);A=Path(os.path.abspath(str(dest)))
	if B==A or A.exists()and B==A.resolve():raise FolderIngestError('Project folder cannot be the same as the iVistaar apps directory.')
	try:A.resolve().relative_to(B);raise FolderIngestError('Deploy target would be inside the project folder; check IVISTAAR_APPS_ROOT.')
	except ValueError:pass
	append_log(D,f"Connected project folder: {B}");append_log(D,f"Syncing into build directory: {A}")
	if A.exists():shutil.rmtree(A)
	A.mkdir(parents=True,exist_ok=True)
	def G(_directory,names):return{A for A in names if A in IGNORE_NAMES or A.endswith(F)}
	for C in B.iterdir():
		if C.name in IGNORE_NAMES or C.name.endswith(F):continue
		E=A/C.name
		if C.is_dir():shutil.copytree(C,E,ignore=G)
		else:shutil.copy2(C,E)
	append_log(D,'Folder sync complete');return A
