#!/usr/bin/make -f
# You must remove unused comment lines for the released package.
export DH_VERBOSE=1

%:
	dh $@

override_dh_auto_build:
	# First build the Python package normally
	dh_auto_build
	
	# Then build PyInstaller executable
	if [ ! -f dist/llm-sdk ]; then \
		pip install uv -i https://nexus.bianbu.xyz/repository/pypi/simple --trusted-host nexus.bianbu.xyz --break-system-packages --prefer-binary; \
		export UV_INDEX_URL=https://mirrors.aliyun.com/pypi/simple; \
		export UV_EXTRA_INDEX_URL=https://git.spacemit.com/api/v4/projects/33/packages/pypi/simple; \
		COUNT=0; MAX_RETRIES=20; \
		until uv sync; do \
			COUNT=$$((COUNT+1)); \
			if [ $$COUNT -ge $$MAX_RETRIES ]; then \
				echo "uv sync 重试 $$MAX_RETRIES 次仍然失败，退出"; \
				exit 1; \
			fi; \
			echo "uv sync 失败，第 $$COUNT 次重试..."; \
			sleep 5; \
		done; \
		uv run pyinstaller --onefile --name llm-sdk --distpath ./dist \
			--hidden-import=langchain_core \
			--hidden-import=langchain_core.messages \
			--hidden-import=langchain_core.prompts \
			--hidden-import=langchain_core.runnables \
			--hidden-import=langchain_core.output_parsers \
			--hidden-import=langchain_core.chat_history \
			--hidden-import=langchain_core.language_models \
			--hidden-import=langchain_core.callbacks \
			--hidden-import=langchain_core.documents \
			--hidden-import=langchain_core.embeddings \
			--hidden-import=langchain_core.vectorstores \
			--hidden-import=langchain_core.retrievers \
			--hidden-import=langchain_core.outputs \
			--hidden-import=langchain_community \
			--hidden-import=langchain_community.embeddings \
			--hidden-import=langchain_community.vectorstores \
			--hidden-import=langchain_chroma \
			--hidden-import=langchain_text_splitters \
			--hidden-import=chromadb \
			--hidden-import=chromadb.config \
			--hidden-import=chromadb.api \
			--hidden-import=chromadb.api.client \
			--hidden-import=chromadb.api.models \
			--hidden-import=pydantic \
			--hidden-import=pydantic_core \
			--collect-all langchain_core \
			--collect-all langchain_community \
			--collect-all langchain_chroma \
			--collect-all langchain_text_splitters \
			--collect-all chromadb \
			--collect-all pydantic \
			--collect-all unstructured \
			main.py; \
	fi

override_dh_auto_clean:
	# Clean build artifacts
	dh_auto_clean
	# Remove uv and cache directories
	rm -rf dist
