import datetime
import io
import zipfile
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextvars import copy_context
from pathlib import Path
from .gallery import GalleryError, PhotoCount, image_index, resolve_gallery

from PIL import Image, ImageOps

from . import runtime_paths

from .local_io import read_file_bytes

MAX_IMAGE_WORKERS = 4

_ASSET_CACHE = {
    "offers": {},
    "agent_photos": {},
}


def _is_offer_image_name(filename: str, estate_id) -> bool:
    return image_index(filename, estate_id) is not None


def _open_remote_client():
    raise RuntimeError("Remote filesystem access is disabled in the isolated engine")


def _read_remote_bytes(remote_path: str):
    try:
        return read_file_bytes(remote_path)
    except Exception:
        return None


def _read_local_then_remote(local_path, remote_path: str):
    if local_path is not None:
        try:
            return local_path.read_bytes()
        except FileNotFoundError:
            pass
    return _read_remote_bytes(remote_path)


def _read_offer_file(estate_id, filename: str):
    local_dir = runtime_paths.local_offer_dir(estate_id)
    return _read_local_then_remote(
        local_dir / filename if local_dir else None,
        runtime_paths.remote_offer_file(estate_id, filename),
    )


def get_description(estate_id):
    description = None
    try:
        local_dir = runtime_paths.local_offer_dir(estate_id)
        description_path = local_dir / f"description_{estate_id}.md" if local_dir else None
        if description_path and description_path.exists():
            description = description_path.read_text(encoding="utf-8")
            return description
    except OSError as e:
        print(f"An error occurred: {str(e)}")

    try:
        remote_path = runtime_paths.remote_offer_file(estate_id, f"description_{estate_id}.md")
        client = _open_remote_client()
        try:
            with client.open_sftp() as sftp:
                with sftp.file(remote_path, "rb") as remote_file:
                    description = remote_file.read().decode("utf-8")
                    return description
        finally:
            client.close()
    except Exception:
        return description

    return description


def count_photos(estate_id):
    folder = runtime_paths.local_offer_dir(estate_id)
    if folder is not None and folder.is_dir():
        names = resolve_gallery((p.name for p in folder.iterdir() if p.is_file()), estate_id)
        return PhotoCount(names, "local")
    return PhotoCount((), "local")



def overlay_logo_bytes(image_bytes, logo_bytes, logo_width_scale=0.4, transparency=200):
    base_image = Image.open(io.BytesIO(image_bytes)).convert("RGBA")
    logo = Image.open(io.BytesIO(logo_bytes)).convert("RGBA")

    logo_width = int(base_image.width * logo_width_scale)
    aspect_ratio = logo.height / logo.width
    logo_height = int(logo_width * aspect_ratio)
    logo = logo.resize((logo_width, logo_height), Image.Resampling.LANCZOS)

    alpha = logo.split()[3]
    alpha = Image.eval(alpha, lambda a: int(a * (transparency / 255.0)))
    logo.putalpha(alpha)

    position = ((base_image.width - logo_width) // 2, (base_image.height - logo_height) // 2)
    base_image_copy = base_image.copy()
    base_image_copy.paste(logo, position, logo)

    output = io.BytesIO()
    base_image_copy.convert("RGB").save(output, format="JPEG")
    return output.getvalue()


def _get_offer_cache_entry(estate_id):
    key = str(estate_id)
    if key not in _ASSET_CACHE["offers"]:
        _ASSET_CACHE["offers"][key] = {
            "raw_images": {},
            "watermarked_images": {},
            "logo_bytes": None,
        }
    return _ASSET_CACHE["offers"][key]


def _load_missing_images_parallel(estate_id, missing_indexes, selection=None):
    selection = selection if selection is not None else count_photos(estate_id)
    if not missing_indexes:
        return {}
    filenames = {idx: selection.names[idx] for idx in missing_indexes}

    def read_selected(name):
        # Do not silently switch source directories after selection.
        if selection.source == "local":
            path = runtime_paths.local_offer_dir(estate_id) / name
            body = read_file_bytes(runtime_paths.checked_path(path))
        else:
            body = _read_remote_bytes(runtime_paths.remote_offer_file(estate_id, name))
        if not body:
            raise GalleryError(f"Selected photo unavailable for offer {estate_id}: {name}")
        if Path(name).suffix.lower() == ".png":
            # Preserve the PNG original; only the ZIP payload is encoded as JPEG.
            with Image.open(io.BytesIO(body)) as image:
                image = ImageOps.exif_transpose(image).convert("RGB")
                output = io.BytesIO()
                image.save(output, format="JPEG", quality=95)
                body = output.getvalue()
        return body

    loaded = {}
    with ThreadPoolExecutor(max_workers=max(1, min(MAX_IMAGE_WORKERS, len(filenames)))) as pool:
        futures = {pool.submit(copy_context().run, read_selected, name): idx for idx, name in filenames.items()}
        for future in as_completed(futures):
            loaded[futures[future]] = future.result()
    return loaded


def _get_offer_images(estate_id, num_photos):
    current = count_photos(estate_id)
    selection = num_photos if isinstance(num_photos, PhotoCount) else current
    if (len(selection.names) != int(num_photos) or current.names != selection.names
            or current.source != selection.source):
        raise GalleryError(f"Photo selection changed for offer {estate_id}")
    # Scope the old asset cache to this read; no stale bytes/watermark by index.
    entry = _get_offer_cache_entry(estate_id)
    entry["watermarked_images"].clear()
    entry["raw_images"] = _load_missing_images_parallel(estate_id, range(int(selection)), selection)
    return entry["raw_images"]


def _get_logo_bytes(estate_id):
    entry = _get_offer_cache_entry(estate_id)
    if entry["logo_bytes"] is None:
        entry["logo_bytes"] = load_watermark_logo_bytes()
    return entry["logo_bytes"]


def load_watermark_logo_bytes():
    """IDBManager's own versioned watermark; never fetched from the Investment server."""
    try:
        return runtime_paths.WATERMARK_LOGO_PATH.read_bytes()
    except OSError as exc:
        print(f"Watermark not available ({runtime_paths.WATERMARK_LOGO_PATH.name}): {exc}")
        return None


def _get_watermarked_image(estate_id, idx, image_bytes, logo_bytes):
    entry = _get_offer_cache_entry(estate_id)
    wm_cache = entry["watermarked_images"]
    if idx in wm_cache:
        return wm_cache[idx]
    wm_cache[idx] = overlay_logo_bytes(image_bytes, logo_bytes)
    return wm_cache[idx]


def _get_agent_photo_bytes(agent_id):
    key = str(agent_id)
    if key not in _ASSET_CACHE["agent_photos"]:
        _ASSET_CACHE["agent_photos"][key] = _read_local_then_remote(
            runtime_paths.local_agent_photo(agent_id),
            runtime_paths.remote_agent_photo(agent_id),
        )
    return _ASSET_CACHE["agent_photos"][key]


def package_files(estate_id, num_photos, generated_xml, option, agent_id):
    zip_filename = f"no_{estate_id}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        if option == "Dodaj":
            logo_bytes = _get_logo_bytes(estate_id)
            images = _get_offer_images(estate_id, num_photos)
            for i in range(num_photos):
                image_bytes = images.get(i)
                if not image_bytes:
                    continue

                if i < (num_photos - 1) and logo_bytes:
                    image_bytes = _get_watermarked_image(estate_id, i, image_bytes, logo_bytes)

                zipf.writestr(f"image_{estate_id}_url_{i}.jpg", image_bytes)

            agent_photo_bytes = _get_agent_photo_bytes(agent_id)
            if agent_photo_bytes:
                zipf.writestr(f"agent_{agent_id}.jpg", agent_photo_bytes)

        zipf.writestr("data.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


def package_files_od(estate_id, num_photos, generated_xml, option, agent_id):
    zip_filename = f"od_{estate_id}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        if option == "Dodaj":
            logo_bytes = _get_logo_bytes(estate_id)
            images = _get_offer_images(estate_id, num_photos)
            for i in range(num_photos):
                image_bytes = images.get(i)
                if not image_bytes:
                    continue

                if i < (num_photos - 1) and logo_bytes:
                    image_bytes = _get_watermarked_image(estate_id, i, image_bytes, logo_bytes)

                zipf.writestr(f"image_{estate_id}_url_{i}.jpg", image_bytes)

            agent_photo_bytes = _get_agent_photo_bytes(agent_id)
            if agent_photo_bytes:
                zipf.writestr(f"agent_{agent_id}.jpg", agent_photo_bytes)

        zipf.writestr("data.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


def package_files_dp(estate_id, num_photos, generated_xml, option, agent_id):
    now = datetime.datetime.now()
    date_str = now.strftime("%Y%m%d%H%M%S")
    zip_filename = f"domiporta_{estate_id}_{date_str}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        if option == "Dodaj":
            logo_bytes = _get_logo_bytes(estate_id)
            images = _get_offer_images(estate_id, num_photos)
            for i in range(num_photos):
                image_bytes = images.get(i)
                if not image_bytes:
                    continue

                if i < (num_photos - 1) and logo_bytes:
                    image_bytes = _get_watermarked_image(estate_id, i, image_bytes, logo_bytes)

                zipf.writestr(f"image_{estate_id}_url_{i}.jpg", image_bytes)

        zipf.writestr("Domiporta.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


def package_files_to(estate_id, num_photos, generated_xml, option, agent_id):
    date_str = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
    zip_filename = f"to_{estate_id}_{date_str}.zip"
    zip_buffer = io.BytesIO()

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        if option == "Dodaj":
            logo_bytes = _get_logo_bytes(estate_id)
            images = _get_offer_images(estate_id, num_photos)
            for i in range(num_photos):
                image_bytes = images.get(i)
                if not image_bytes:
                    continue

                if i < (num_photos - 1) and logo_bytes:
                    image_bytes = _get_watermarked_image(estate_id, i, image_bytes, logo_bytes)

                zipf.writestr(f"image_{estate_id}_url_{i}.jpg", image_bytes)

        zipf.writestr("oferty.xml", generated_xml.encode("utf-8"))

    return zip_filename, zip_buffer.getvalue()


def package_files_gruntguru(estate_id, num_photos, generated_xml, option, agent_id, company_id="0"):
    date_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    zip_filename = f"gruntguru_{estate_id}_{date_str}.zip"
    xml_filename = f"EstiCRM_{company_id}_{date_str}.xml"
    zip_buffer = io.BytesIO()
    definitions_path = Path(__file__).resolve().parent / "portals" / "gruntguru" / "EstiCRM_XML_example" / "definitions.xml"

    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf:
        if option == "Dodaj":
            logo_bytes = _get_logo_bytes(estate_id)
            images = _get_offer_images(estate_id, num_photos)
            for i in range(num_photos):
                image_bytes = images.get(i)
                if not image_bytes:
                    continue

                if i < (num_photos - 1) and logo_bytes:
                    image_bytes = _get_watermarked_image(estate_id, i, image_bytes, logo_bytes)

                zipf.writestr(f"image_{estate_id}_url_{i}.jpg", image_bytes)

        zipf.writestr(xml_filename, generated_xml.encode("utf-8"))

        if definitions_path.exists():
            zipf.writestr("definitions.xml", definitions_path.read_bytes())

    return zip_filename, zip_buffer.getvalue()
