# -*- coding: utf-8 -*-
from setupdevhelpers import *
import os
import shutil
import os
import glob
import distro
import platform

python_name_file = str(platform.system().lower() + '_' + platform.machine().lower() + '_' + '_'.join([u.split('.')[0] for u in distro.linux_distribution(False) if u][:2])).strip('_')


def update_package():

    colum1 = bs_find_all('https://www.python.org/downloads/source/','div','class',"column")[0].findAll('li')
    versionpython = None
    for entry in colum1:
        if versionpython:
            continue
        if not hasattr(entry,'contents'):
            continue
        for i in entry.contents :
            if not hasattr(i,'contents'):
                continue
            v = [t for t in i.contents if str(t).startswith('Python 3.10')]
            if v:
                versionpython = v[0].split(' ')[1]
                break

    openssl_version = '3.5.4'

    #Download and extract python source
    wget(f'https://www.python.org/ftp/python/{versionpython}/Python-{versionpython}.tgz',f'Python-{versionpython}.tgz')
    unzip_with_7zip(f'Python-{versionpython}.tgz',f'Python-{versionpython}-tar')
    unzip_with_7zip(rf'Python-{versionpython}-tar\Python-{versionpython}.tar','.')

    remove_tree(f'Python-{versionpython}-tar')
    remove_file(f'Python-{versionpython}.tgz')

    #Download and extract openssl source
    wget(rf'https://github.com/openssl/openssl/releases/download/openssl-{openssl_version}/openssl-{openssl_version}.tar.gz',rf'openssl-{openssl_version}.tar.gz')
    unzip_with_7zip(rf'openssl-{openssl_version}.tar.gz',rf'openssl-{openssl_version}-tar')
    unzip_with_7zip(rf'openssl-{openssl_version}-tar\openssl-{openssl_version}.tar','.')
    remove_tree(rf'openssl-{openssl_version}-tar')
    remove_file(rf'openssl-{openssl_version}.tar.gz')

    if not isfile(r'C:\Program Files\NASM\nasm.exe'):
        error(r'C:\Program Files\NASM\nasm.exe not found')

    run(rf'Python-{versionpython}\PCbuild\get_externals.bat',timeout=5000)

    with open(rf'openssl-{openssl_version}\Configurations\60-custom.conf','w') as f:
        f.write(data_custom)

    add_to_system_path(r'C:\Program Files\NASM')

    run(rf'cd openssl-{openssl_version} & set path=C:\Program Files\NASM;%path% &"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvars64.bat" &"C:\Strawberry\perl\bin\perl.exe" configure VC-WIN64A-rtt & nmake',timeout=5000)
    #run(rf'cd openssl-{openssl_version} & set path=C:\Program Files\NASM;%path% &"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Auxiliary\Build\vcvars32.bat" &"C:\Strawberry\perl\bin\perl.exe" configure VC-WIN32-rtt & nmake',timeout=1200)

    name_openssl_folder = glob.glob(rf'Python-{versionpython}\externals\openssl-bin-*')[0].split('\\')[-1]
    shutil.move(rf'Python-{versionpython}\externals\{name_openssl_folder}\amd64',rf'Python-{versionpython}\externals\{name_openssl_folder}\amd64old')
    shutil.move(rf'openssl-{openssl_version}',rf'Python-{versionpython}\externals\{name_openssl_folder}\amd64')
    filecopyto(rf'Python-{versionpython}\externals\{name_openssl_folder}\amd64old\include\applink.c',rf'Python-{versionpython}\externals\{name_openssl_folder}\amd64\include\applink.c')


    with open(makepath(f'Python-{versionpython}','PCbuild','openssl.props'), 'r') as f:
        data=f.read()
    data = data.replace(r"<_DLLSuffix>-1_1</_DLLSuffix>",r"<_DLLSuffix>-3-x64</_DLLSuffix>")
    with open(makepath(f'Python-{versionpython}','PCbuild','openssl.props'), 'w') as f:
        f.write(data)

    run(rf'Python-{versionpython}\PCbuild\build.bat -t Rebuild',timeout=5000)

    run(rf'"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\msbuild.exe" "%s\Python-{versionpython}\Tools\msi\make_zip.proj" /t:Build /p:Platform=x64 /p:OutputPath="%s"' % (basedir,basedir))

    name_generate = glob.glob('*.zip')[0]
    os.rename(name_generate,'Python-%s-x64.zip' % python_name_file)

    remove_tree(f'Python-{versionpython}')
    commit_count = params.get("commit_count",0)
    control.version = "%s-%s" % (Version(versionpython), commit_count)
    control.save_control_to_wapt()



data_custom = r"""## -*- mode: perl; -*-
## Personal configuration targets

my %targets = (
    "VC-WIN32-rtt" => {
        inherit_from     => [ "VC-WIN32" ],
        cflags           => sub{my $v=pop; $v=~ s/\/MD/\/MT/ig; return $v},
        lflags           => "/nologo /release",
    },
    "VC-WIN64A-rtt" => {
        inherit_from     => [ "VC-WIN64A" ],
        cflags           => sub{my $v=pop; $v=~ s/\/MD/\/MT/ig; return $v},
        lflags           => "/nologo /release",
    },
);"""
