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.2.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 = (
        "a5be08849787b07dd46236e63e47d614db4967e8f14bbf8cfc6b6112925cf437"
        "6bc2f2e0b59b91718dda8e3fd28b39d359248b16524b37752672ecd26678834c"
    )
    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 = (
        "42accd01d5f152a9a6b26883b735242fb6e9eb01f85f3ff752fc970d413c746d"
        "c0a875c89f9e3942012491954d59e3ea2b05ab4419a8876937b73fedb8c29a4e"
    )
    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
