﻿#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import importlib
import random
import shutil
import subprocess
import sys
from pathlib import Path

IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}
BANNER_TEXT = "https://t.me/Code_Solver\nhttps://t.me/CtrlAltCaptcha"
SCRIPT_VERSION = "banner-debug-v7"
MAX_ITEMS_PER_URL = 30
BANNER_MAX_AREA_RATIO = 0.15
UNSPLASH_KEYWORDS = [
    "crypto", "bitcoin", "ethereum", "blockchain", "web3", "defi", "nft", "metaverse",
    "altcoin", "token", "wallet", "ledger", "mining", "hashrate", "staking", "smart-contract",
    "dao", "airdrop", "onchain", "cryptography", "cybersecurity", "encryption", "privacy",
    "firewall", "malware", "phishing", "zero-day", "penetration-testing", "ai", "machine-learning",
    "deep-learning", "neural-network", "data-science", "automation", "robotics", "cloud-computing",
    "serverless", "devops", "kubernetes", "docker", "microservices", "backend", "frontend",
    "fullstack", "programming", "software-engineering", "code", "algorithm", "database",
    "sql", "nosql", "api", "rest-api", "graphql", "typescript", "python", "golang", "rust",
    "javascript", "react", "nodejs", "mobile-development", "ios", "android", "ui-ux",
    "product-design", "startup", "fintech", "quant-trading", "trading-bot", "high-frequency-trading",
    "analytics", "big-data", "data-center", "edge-computing", "iot", "5g", "semiconductor",
    "chip-design", "computer-vision", "augmented-reality", "virtual-reality", "gaming-tech",
    "esports", "digital-economy", "electronic-payments", "biometrics", "identity-verification",
    "open-source", "git", "ci-cd", "testing", "performance", "scalability", "latency",
    "observability", "monitoring", "telemetry", "infrastructure", "innovation",
]


def build_random_unsplash_url() -> str:
    keyword = random.choice(UNSPLASH_KEYWORDS)
    return f"https://unsplash.com/s/photos/{keyword}"


def _run_command(cmd: list[str]) -> bool:
    try:
        subprocess.check_call(cmd)
        return True
    except Exception:
        return False


def get_pip_command() -> list[str] | None:
    try:
        import pip  # noqa: F401
        return [sys.executable, "-m", "pip"]
    except Exception:
        pass

    # Try to bootstrap pip for the current interpreter
    _run_command([sys.executable, "-m", "ensurepip", "--upgrade"])

    try:
        import pip  # noqa: F401
        return [sys.executable, "-m", "pip"]
    except Exception:
        pass

    # Windows fallback: use launcher
    if _run_command(["py", "-m", "pip", "--version"]):
        return ["py", "-m", "pip"]
    return None


def ensure_gallery_dl() -> str:
    """
    Returns path to gallery-dl executable if available.
    Tries to install with pip if missing.
    """
    exe = shutil.which("gallery-dl")
    if exe:
        return exe

    print("[!] gallery-dl bulunamadi. pip ile kuruluyor...", file=sys.stderr)
    pip_cmd = get_pip_command()
    if not pip_cmd:
        raise SystemExit(
            "[x] pip bulunamadi. Aktif interpreter: "
            f"{sys.executable}\n"
            "Su komutlardan birini deneyin:\n"
            "  python -m ensurepip --upgrade\n"
            "  py -m ensurepip --upgrade"
        )
    try:
        subprocess.check_call([*pip_cmd, "install", "-U", "gallery-dl"])
    except subprocess.CalledProcessError as e:
        raise SystemExit(f"[x] gallery-dl kurulamadı: {e}")

    exe = shutil.which("gallery-dl")
    if not exe:
        raise SystemExit("[x] gallery-dl hala PATH uzerinde degil. Yeni terminal acip tekrar dene.")
    return exe


def ensure_pillow():
    """
    Returns Pillow modules (Image, ImageDraw, ImageFont).
    Tries to install with pip if missing.
    """
    try:
        Image = importlib.import_module("PIL.Image")
        ImageDraw = importlib.import_module("PIL.ImageDraw")
        ImageFont = importlib.import_module("PIL.ImageFont")
        return Image, ImageDraw, ImageFont
    except Exception:
        pass

    print("[!] Pillow bulunamadi. pip ile kuruluyor...", file=sys.stderr)
    pip_cmd = get_pip_command()
    if not pip_cmd:
        raise SystemExit(
            "[x] pip bulunamadi. Aktif interpreter: "
            f"{sys.executable}\n"
            "Su komutlardan birini deneyin:\n"
            "  python -m ensurepip --upgrade\n"
            "  py -m ensurepip --upgrade"
        )
    try:
        subprocess.check_call([*pip_cmd, "install", "-U", "pillow"])
    except subprocess.CalledProcessError as e:
        raise SystemExit(f"[x] Pillow kurulamadı: {e}")

    try:
        Image = importlib.import_module("PIL.Image")
        ImageDraw = importlib.import_module("PIL.ImageDraw")
        ImageFont = importlib.import_module("PIL.ImageFont")
        return Image, ImageDraw, ImageFont
    except Exception as e:
        raise SystemExit(f"[x] Pillow import edilemedi: {e}")


def is_image_file(path: Path) -> bool:
    return path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS


def collect_image_files(base_dir: Path) -> list[Path]:
    if not base_dir.exists():
        return []
    return sorted(path.resolve() for path in base_dir.rglob("*") if is_image_file(path))


def load_banner_font(ImageFont, font_size: int):
    candidates = [
        "C:/Windows/Fonts/arial.ttf",
        "C:/Windows/Fonts/segoeui.ttf",
        "C:/Windows/Fonts/tahoma.ttf",
        "DejaVuSans.ttf",
    ]
    for font_path in candidates:
        try:
            return ImageFont.truetype(font_path, size=font_size)
        except Exception:
            continue
    return ImageFont.load_default()


def apply_subtle_banner(image_path: Path, image_libs) -> tuple[bool, str]:
    Image, ImageDraw, ImageFont = image_libs
    try:
        with Image.open(image_path) as img:
            base = img.convert("RGBA")
            overlay = Image.new("RGBA", base.size, (0, 0, 0, 0))
            draw = ImageDraw.Draw(overlay)
            image_area = max(1, base.width * base.height)
            max_banner_area = int(image_area * BANNER_MAX_AREA_RATIO)

            font_size = max(18, int(min(base.size) * 0.12))
            font = load_banner_font(ImageFont, font_size)
            spacing = max(4, int(font_size * 0.25))
            bbox = draw.multiline_textbbox((0, 0), BANNER_TEXT, font=font, spacing=spacing)
            text_w = max(1, bbox[2] - bbox[0])
            text_h = max(1, bbox[3] - bbox[1])

            while (text_w * text_h) > max_banner_area and font_size > 12:
                font_size = max(12, int(font_size * 0.9))
                font = load_banner_font(ImageFont, font_size)
                spacing = max(3, int(font_size * 0.22))
                bbox = draw.multiline_textbbox((0, 0), BANNER_TEXT, font=font, spacing=spacing)
                text_w = max(1, bbox[2] - bbox[0])
                text_h = max(1, bbox[3] - bbox[1])
            margin = max(12, int(min(base.size) * 0.03))
            x = max(margin, base.width - text_w - margin)
            y = max(margin, base.height - text_h - margin)

            # Slightly stronger visibility while still subtle:
            # draw a soft dark strip under text + semi-transparent white text.
            strip_pad_x = max(8, int(font_size * 0.6))
            strip_pad_y = max(6, int(font_size * 0.45))
            strip_box = (
                max(0, x - strip_pad_x),
                max(0, y - strip_pad_y),
                min(base.width, x + text_w + strip_pad_x),
                min(base.height, y + text_h + strip_pad_y),
            )
            draw.rectangle(strip_box, fill=(0, 0, 0, 38))

            alpha = max(45, min(70, int(min(base.size) * 0.06)))
            draw.multiline_text(
                (x + 1, y + 1),
                BANNER_TEXT,
                font=font,
                spacing=spacing,
                fill=(0, 0, 0, max(18, alpha // 2)),
            )
            draw.multiline_text(
                (x, y),
                BANNER_TEXT,
                font=font,
                spacing=spacing,
                fill=(255, 255, 255, alpha),
            )

            composited = Image.alpha_composite(base, overlay)
            suffix = image_path.suffix.lower()
            if suffix in {".jpg", ".jpeg"}:
                composited.convert("RGB").save(image_path, format="JPEG", quality=95, optimize=True)
            elif suffix == ".png":
                composited.save(image_path, format="PNG", optimize=True)
            elif suffix == ".webp":
                composited.save(image_path, format="WEBP", quality=95, method=6)
            else:
                composited.save(image_path)
        return True, ""
    except Exception as exc:
        return False, str(exc)


def watermark_images(image_files: list[Path], image_libs) -> tuple[int, int]:
    if not image_files:
        print("[i] Banner icin hedef image bulunamadi.", flush=True)
        return 0, 0

    print(f"[i] Banner uygulanacak image sayisi: {len(image_files)}", flush=True)
    ok_count = 0
    fail_count = 0
    for image_path in image_files:
        ok, err = apply_subtle_banner(image_path, image_libs)
        if ok:
            ok_count += 1
            print(f"[ok] Banner: {image_path.name}", flush=True)
        else:
            fail_count += 1
            print(f"[!] Banner uygulanamadi: {image_path} -> {err}", file=sys.stderr, flush=True)
    return ok_count, fail_count


def _extract_downloaded_image_path(line: str, outdir: Path) -> Path | None:
    candidate = line.strip()
    if not candidate:
        return None

    path = Path(candidate)
    if not path.is_absolute():
        path = outdir / path
    path = path.resolve()
    if not is_image_file(path):
        return None
    return path


def run_gallery_dl(
    exe: str,
    url: str,
    outdir: Path,
    rate: str | None,
    retries: int,
    verbose: bool,
) -> tuple[int, list[Path]]:
    outdir.mkdir(parents=True, exist_ok=True)

    cmd = [
        exe,
        "--directory", str(outdir),
        "--retries", str(retries),
        "--range", f"1-{MAX_ITEMS_PER_URL}",
    ]

    if rate:
        cmd += ["--limit-rate", rate]

    if verbose:
        cmd += ["-v"]

    cmd.append(url)

    print(f"\n[>] Calistiriliyor: {' '.join(cmd)}")
    try:
        process = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding="utf-8",
            errors="replace",
        )
    except FileNotFoundError:
        return 127, []

    downloaded: list[Path] = []
    seen: set[Path] = set()
    assert process.stdout is not None
    for raw_line in process.stdout:
        print(raw_line, end="")
        image_path = _extract_downloaded_image_path(raw_line, outdir)
        if image_path and image_path not in seen:
            seen.add(image_path)
            downloaded.append(image_path)

    code = process.wait()
    return int(code), downloaded


def main():
    parser = argparse.ArgumentParser(
        description="gallery-dl ile Unsplash (ve diger desteklenen siteler) gorsellerini Python uzerinden indir."
    )
    parser.add_argument(
        "urls",
        nargs="*",
        default=[build_random_unsplash_url()],
        help="Indirilecek URL(ler). Ornek: https://unsplash.com/s/photos/nft",
    )
    parser.add_argument(
        "-o", "--out",
        default="downloads",
        help="Cikti klasoru (varsayilan: downloads)",
    )
    parser.add_argument(
        "--rate",
        default=None,
        help="Hiz limiti. Ornek: 2M, 500K (opsiyonel)",
    )
    parser.add_argument(
        "--retries",
        type=int,
        default=5,
        help="Hata olursa tekrar deneme sayisi (varsayilan: 5)",
    )
    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="Detayli log",
    )

    args = parser.parse_args()
    exe = ensure_gallery_dl()
    image_libs = ensure_pillow()

    script_dir = Path(__file__).resolve().parent
    outdir = Path(args.out)
    if not outdir.is_absolute():
        outdir = script_dir / outdir
    outdir = outdir.resolve()
    print(f"[i] Script version: {SCRIPT_VERSION}", flush=True)
    print(f"[i] Cikti klasoru: {outdir}", flush=True)

    exit_code = 0
    for url in args.urls:
        print("[i] Download adimi basliyor...", flush=True)
        code, downloaded_files = run_gallery_dl(exe, url, outdir, args.rate, args.retries, args.verbose)
        print(f"[i] Download adimi bitti. Exit code: {code}", flush=True)
        print("[i] Banner adimi basliyor...", flush=True)
        if not downloaded_files and code == 0:
            # Fallback: if gallery-dl output format changes, do not skip banner entirely.
            downloaded_files = collect_image_files(outdir)
        ok_count, fail_count = watermark_images(downloaded_files, image_libs)
        print(f"[i] Banner uygulandi. Basarili: {ok_count}, Hatali: {fail_count}", flush=True)
        if code != 0:
            print(f"[!] Hata kodu {code}: {url}", file=sys.stderr)
            exit_code = code

    raise SystemExit(exit_code)


if __name__ == "__main__":
    main()
