import shutil
import zipfile
from pathlib import Path

from dev_tools.utility.network import download_check_hash


def cache_tika_server(cache_dir):
    version = "2.9.1"
    tika_dir = cache_dir / "tika" / version
    tika_dir.mkdir(parents=True, exist_ok=True)
    tika_jar_name = cache_tika_server_jar(tika_dir, version)
    cache_tika_legal(tika_dir, cache_dir / "tika_src" / version, version)
    return tika_dir, "\t" + tika_jar_name


def cache_tika_server_jar(tika_dir, version):
    tika_jar_name = f"tika-server-standard-{version}.jar"
    hash_digest = (
        "2650d35be781879f2b13bd623bac6fc4f5d0788fc7a077ecb5c4529bd8e45bb3"
        "40d8a9deb433d87fac151f5bf41e6c91607e55d6ba01021ecf95029992987f78"
    )
    tika_jar = tika_dir / tika_jar_name
    if not tika_jar.exists():
        download_check_hash(
            f"https://dlcdn.apache.org/tika/{version}/{tika_jar_name}",
            hash_digest,
            tika_jar,
        )
    return tika_jar_name


def cache_tika_legal(tika_dir, tika_src_dir, version):
    tika_src_dir.mkdir(parents=True, exist_ok=True)
    tika_src_name = f"tika-{version}-src.zip"
    hash_digest = (
        "ba13a0d22994ca84cccd9ad2931e099051870d46a5a3440258f93bd63f6e3b03"
        "de51709c51cf0e4029e57ba9c44cdb243ac440d76e695dfc081dfd9d956d8777"
    )
    tika_src = tika_src_dir / tika_src_name
    if not tika_src.exists():
        download_check_hash(
            f"https://dlcdn.apache.org/tika/{version}/{tika_src_name}",
            hash_digest,
            tika_src,
        )
    tika_license = tika_dir / "LICENSE.txt"
    if not tika_license.exists():
        with zipfile.ZipFile(tika_src) as f:
            tika_license.write_bytes(f.read(f"tika-{version}/LICENSE.txt"))
    tika_notice = tika_dir / "NOTICE.txt"
    if not tika_notice.exists():
        with zipfile.ZipFile(tika_src) as f:
            tika_notice.write_bytes(f.read(f"tika-{version}/NOTICE.txt"))


def build_deps_tika(deps_dir: Path, tika_dir_path: Path):
    tika_dir = deps_dir / "tika"
    tika_dir.mkdir(parents=True)
    for item in tika_dir_path.iterdir():
        shutil.copy(item, tika_dir / item.name)
    return tika_dir
