import argparse
import hashlib
import io
import json
import os
import re
import sys
import tempfile
from contextlib import contextmanager
from pathlib import Path

from PIL import Image, ImageOps, __version__ as PILLOW_VERSION

_REPO_ROOT = Path(__file__).resolve().parents[1]
if str(_REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(_REPO_ROOT))

from modules.core import storage_paths  # noqa: E402
from InvestmentManager.integrator.input_consistency import serialized_write, write_inputs, write_failed

IMAGE_EXTENSIONS = (".jpg", ".jpeg", ".png")
OFFER_ID_RE = re.compile(r"^\d+$")
LOCK_FILENAME = ".resize_images.lock"
THUMBNAIL_SIZE = (400, 300)
THUMBNAIL_QUALITY = 75
THUMBNAIL_RECIPE_VERSION = 1
THUMBNAIL_SIGNATURE_TAG = 270  # EXIF ImageDescription; only derived thumbnail metadata.


def _stats():
    return {
        "offers_scanned": 0,
        "conversions": 0,
        "conversion_skips": 0,
        "resizes": 0,
        "thumbnails": 0,
        "thumbnail_skips": 0,
        "missing_thumbnail_sources": 0,
        "errors": 0,
    }


def _validate_offer_id(value):
    if not OFFER_ID_RE.fullmatch(value or ""):
        raise argparse.ArgumentTypeError("offer-id must contain digits only")
    return value


def _as_jpeg_compatible(img):
    if img.mode in ("RGBA", "P") or img.mode != "RGB":
        return img.convert("RGB")
    return img


@serialized_write
def _atomic_save(img, target_path, *, image_format=None, **save_kwargs):
    target = Path(target_path)
    if target.is_symlink() or target.parent.is_symlink() or target.parent.is_junction():
        raise ValueError("Image paths must not be links")
    if target.name.lower().startswith("image_") and target.parent.name.isdecimal():
        write_inputs(offer_ids=[int(target.parent.name)])
    fd, tmp_name = tempfile.mkstemp(
        prefix=f".{target.name}.",
        suffix=".tmp",
        dir=str(target.parent),
    )
    os.close(fd)
    tmp_path = Path(tmp_name)
    try:
        img.save(tmp_path, format=image_format, **save_kwargs)
        os.replace(tmp_path, target)
    except Exception:
        try:
            tmp_path.unlink()
        except OSError:
            pass
        raise


def _iter_offer_dirs(offers_root, offer_id=None):
    root = Path(offers_root)
    if offer_id is not None:
        yield root / offer_id
        return

    if not root.exists():
        return

    for path in sorted(root.iterdir(), key=lambda item: item.name):
        if path.is_dir() and OFFER_ID_RE.fullmatch(path.name):
            yield path


@serialized_write(dry_run=True)
def normalize_extensions(offer_dirs, *, dry_run=False, stats=None):
    """Retain source names/bytes. Export now resolves JPEG extensions directly.

    PNG conversion is deferred until a source/derived directory contract is agreed.
    This compatibility entry point only detects collisions; it never deletes files.
    """
    stats = stats if stats is not None else _stats()
    for offer_dir in offer_dirs:
        if not offer_dir.is_dir():
            continue
        try:
            seen = set()
            if offer_dir.is_symlink() or offer_dir.is_junction():
                raise ValueError("Offer directory must not be a link")
            for path in offer_dir.iterdir():
                if path.suffix.lower() not in IMAGE_EXTENSIONS:
                    continue
                if path.is_symlink():
                    raise ValueError("Image source must not be a link")
                if not path.is_file():
                    continue
                # A would-be conversion must never silently pick a winner.
                stem = path.stem.lower()
                if stem in seen:
                    raise ValueError(f"Ambiguous image sources: {stem}")
                seen.add(stem)
                if path.suffix.lower() != ".jpg":
                    stats["conversion_skips"] += 1
        except (OSError, ValueError) as exc:
            stats["errors"] += 1
            print(f"Unsafe image conversion skipped: {exc}")
    return stats


@serialized_write(dry_run=True)
def resize_large_images(offer_dirs, *, min_dimension=2900, dry_run=False, stats=None):
    stats = stats if stats is not None else _stats()
    for offer_dir in offer_dirs:
        if not offer_dir.is_dir():
            continue

        if offer_dir.is_symlink() or offer_dir.is_junction():
            stats["errors"] += 1
            continue
        for path in sorted(offer_dir.iterdir(), key=lambda item: item.name):
            if path.is_symlink():
                stats["errors"] += 1
                continue
            if not path.is_file() or path.suffix.lower() not in IMAGE_EXTENSIONS:
                continue

            try:
                with Image.open(path) as img:
                    img = ImageOps.exif_transpose(img)
                    width, height = img.size
                    if width <= min_dimension and height <= min_dimension:
                        continue

                    new_width = width // 2
                    new_height = height // 2
                    stats["resizes"] += 1
                    if dry_run:
                        print(f"Would resize: {path} ({width}x{height} -> {new_width}x{new_height})")
                        continue

                    resized = img.resize((new_width, new_height), Image.LANCZOS)
                    save_format = "JPEG" if path.suffix.lower() in (".jpg", ".jpeg") else "PNG"
                    _atomic_save(resized, path, image_format=save_format)
                    print(f"Successfully resized: {path} (new size: {new_width}x{new_height})")
            except Exception as exc:
                write_failed()
                stats["errors"] += 1
                print(f"Failed to process {path}: {exc}")

    return stats


def _thumbnail_source(offer_dir):
    """Resolve one main source without renaming or choosing among duplicates."""
    if offer_dir.is_symlink() or offer_dir.is_junction():
        raise ValueError("Offer directory must not be a link")
    stem = f"image_{offer_dir.name}_url_0"
    candidates = sorted(
        (path for path in offer_dir.iterdir()
         if path.stem.lower() == stem.lower()
         and path.suffix.lower() in IMAGE_EXTENSIONS and (path.is_file() or path.is_symlink())),
        key=lambda path: path.name,
    )
    if len(candidates) > 1:
        raise ValueError(f"Ambiguous thumbnail sources in {offer_dir}")
    if candidates and candidates[0].is_symlink():
        raise ValueError("Thumbnail source must not be a link")
    return candidates[0] if candidates else None


def _thumbnail_signature(source, body):
    return json.dumps({
        "source": source.name, "sha256": hashlib.sha256(body).hexdigest(),
        "size": THUMBNAIL_SIZE, "quality": THUMBNAIL_QUALITY,
        "recipe": THUMBNAIL_RECIPE_VERSION, "pillow": PILLOW_VERSION,
        "resampling": "LANCZOS", "exif_transpose": True, "mode": "RGB",
    }, sort_keys=True, separators=(",", ":"))


def _thumbnail_current(path, signature):
    if path.is_symlink():
        raise ValueError("Thumbnail target must not be a link")
    try:
        with Image.open(path) as image:
            if (image.format != "JPEG" or image.size != THUMBNAIL_SIZE
                    or image.getexif().get(THUMBNAIL_SIGNATURE_TAG) != signature):
                return False
            image.load()  # Regenerate damaged output even if its metadata survived.
            return True
    except (OSError, ValueError, SyntaxError):
        return False


@serialized_write(dry_run=True)
def create_or_update_thumbnails(offer_dirs, *, dry_run=False, stats=None):
    stats = stats if stats is not None else _stats()
    for offer_dir in offer_dirs:
        if not offer_dir.is_dir():
            continue

        try:
            image_path = _thumbnail_source(offer_dir)
        except (OSError, ValueError) as exc:
            stats["errors"] += 1
            print(f"Failed to select thumbnail source: {exc}")
            continue
        if image_path is None:
            stats["missing_thumbnail_sources"] += 1
            continue

        thumbnail_path = offer_dir / "thumbnail.jpg"
        try:
            body = image_path.read_bytes()
            signature = _thumbnail_signature(image_path, body)
            if _thumbnail_current(thumbnail_path, signature):
                stats["thumbnail_skips"] += 1
                continue
            if dry_run:
                stats["thumbnails"] += 1
                print(f"Would generate thumbnail: {thumbnail_path}")
                continue
            with Image.open(io.BytesIO(body)) as img:
                img = ImageOps.exif_transpose(img)
                img = img.resize(THUMBNAIL_SIZE, Image.LANCZOS)
                img = _as_jpeg_compatible(img)
                metadata = Image.Exif()
                metadata[THUMBNAIL_SIGNATURE_TAG] = signature
                _atomic_save(img, thumbnail_path, image_format="JPEG",
                             quality=THUMBNAIL_QUALITY, exif=metadata)
            stats["thumbnails"] += 1
        except Exception as exc:
            stats["errors"] += 1
            print(f"Failed to create or update thumbnail for {image_path}: {exc}")

    return stats


@contextmanager
def process_lock(offers_root, *, dry_run=False):
    if dry_run:
        yield True
        return

    if os.name != "posix":
        yield True
        return

    import fcntl

    lock_path = Path(offers_root) / LOCK_FILENAME
    with open(lock_path, "a", encoding="utf-8") as lock_file:
        try:
            fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            print("Another resize_images.py run is already active; exiting.")
            yield False
            return
        try:
            yield True
        finally:
            fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)


def run(*, offer_id=None, dry_run=False):
    offers_root = storage_paths.offers_root_dir()
    offer_dirs = list(_iter_offer_dirs(offers_root, offer_id))
    stats = _stats()
    stats["offers_scanned"] = len([path for path in offer_dirs if path.is_dir()])

    print(f"Offers root: {offers_root}")
    if offer_id:
        print(f"Offer scope: {offer_id}")
    if dry_run:
        print("Dry run: no files will be changed.")

    normalize_extensions(offer_dirs, dry_run=dry_run, stats=stats)
    # A collision must stop in-place resize, even though originals are retained.
    if not stats["errors"]:
        resize_large_images(offer_dirs, dry_run=dry_run, stats=stats)
    create_or_update_thumbnails(offer_dirs, dry_run=dry_run, stats=stats)

    print(
        "Summary: "
        f"offers={stats['offers_scanned']}, "
        f"conversions={stats['conversions']}, "
        f"conversion_skips={stats['conversion_skips']}, "
        f"resizes={stats['resizes']}, "
        f"thumbnails={stats['thumbnails']}, "
        f"thumbnail_skips={stats['thumbnail_skips']}, "
        f"missing_thumbnail_sources={stats['missing_thumbnail_sources']}, "
        f"errors={stats['errors']}"
    )
    print("End of resizing")
    return stats


def parse_args(argv=None):
    parser = argparse.ArgumentParser(
        description="Resize Investment offer images under the canonical DATA_DIR/offers root."
    )
    parser.add_argument("--dry-run", action="store_true", help="Inspect images and print planned changes only.")
    parser.add_argument("--offer-id", type=_validate_offer_id, help="Process only one numeric offer directory.")
    return parser.parse_args(argv)


def main(argv=None):
    args = parse_args(argv)
    offers_root = storage_paths.offers_root_dir()
    with process_lock(offers_root, dry_run=args.dry_run) as acquired:
        if not acquired:
            return 2
        stats = run(offer_id=args.offer_id, dry_run=args.dry_run)
    return 1 if stats["errors"] else 0


if __name__ == "__main__":
    raise SystemExit(main())
