import os
import subprocess
from urllib.parse import urlparse
import argparse


class HarmonyAppInstaller:
    def __init__(self) -> None:
        self.project_path = os.getcwd()
        self.temp_dir = os.path.join(self.project_path, "temp")

    def _run_command(self, command: str) -> str:
        result = subprocess.run(command, shell=True, capture_output=True, text=True)
        if result.returncode != 0:
            raise Exception(f"Command failed: {command}\nError: {result.stderr}")
        return result.stdout

    def install(self, appUniqId, packageId):
        import requests
        import os
        import shutil

        # Create or clean temp directory
        if os.path.exists(self.temp_dir):
            shutil.rmtree(self.temp_dir)
        os.makedirs(self.temp_dir)

        url = "https://api.qa.huohua.cn/api/versions"

        headers = {
            'Content-Type': 'application/json',
            'huohua-podenv': 'HHC-111781'
        }

        params = {
            'version': '25.1.2.1',
            'platform': 'harmonyos',
            'appUniqId': appUniqId,
            'packageId': packageId
        }

        response = requests.get(url, headers=headers, params=params)
        response_data = response.json()

        if not response_data.get('success'):
            raise Exception(f"API request failed: {response_data.get('message')}")

        app_version = response_data.get('data', {}).get('app_version', {})
        download_url = app_version.get('url')

        if not download_url:
            raise Exception("No download URL found in response")

        # Get the filename from the URL
        hap_filename = os.path.basename(urlparse(download_url).path)
        if not hap_filename.endswith('.hap'):
            hap_filename = 'eduparent.hap'  # fallback name if URL doesn't end with .hap

        # Download the HAP file
        hap_file_path = os.path.join(self.temp_dir, hap_filename)
        download_response = requests.get(download_url, stream=True)
        download_response.raise_for_status()

        with open(hap_file_path, 'wb') as f:
            for chunk in download_response.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)

        # Execute HDC commands
        device_path = f"data/local/tmp/{hap_filename}"

        print(f'hdc file send "{hap_file_path}" "{device_path}"')
        # Push HAP file to device
        self._run_command(f'hdc file send "{hap_file_path}" "{device_path}"')

        try:
            # Install HAP package
            print(f'hdc shell bm install -p "{device_path}"')
            self._run_command(f'hdc shell bm install -p "{device_path}"')
        finally:
            # Clean up: Remove HAP file from device
            print(f'hdc shell rm -rf "{device_path}"')
            self._run_command(f'hdc shell rm -rf "{device_path}"')

        return hap_file_path


def main():
    parser = argparse.ArgumentParser(description='Install HarmonyOS application')
    parser.add_argument('--app-uniq-id', required=True, help='Unique ID of the application')
    parser.add_argument('--package-id', required=True, help='Package ID for the application')

    args = parser.parse_args()

    try:
        installer = HarmonyAppInstaller()
        hap_path = installer.install(args.app_uniq_id, args.package_id)
        print(f"Successfully installed HAP from: {hap_path}")
    except Exception as e:
        print(f"Error: {str(e)}")
        exit(1)


if __name__ == '__main__':
    main()
