import os
from pathlib import Path
from urllib.parse import urlparse

from dotenv import load_dotenv

PROJECT_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_LICENSE_API_BASE = "https://api.everflow.cc"


def _default_data_dir() -> Path:
    """Prefer Application Support once a desktop migration has landed there."""
    app_support = Path.home() / "Library" / "Application Support" / "PhotoPick"
    if (app_support / "photopick.json").exists():
        return app_support
    return PROJECT_ROOT / "data"


def _running_from_app_bundle() -> bool:
    """True when code lives inside a macOS .app (packaged release)."""
    return ".app/Contents/" in str(PROJECT_ROOT.resolve())


def _is_loopback_url(url: str) -> bool:
    host = (urlparse((url or "").strip()).hostname or "").lower()
    return host in {"127.0.0.1", "localhost", "::1"}


# Project .env first (dev), then data-dir .env can override (desktop).
load_dotenv(PROJECT_ROOT / ".env")
DATA_DIR = Path(os.environ.get("PHOTOPICK_DATA_DIR", str(_default_data_dir())))
load_dotenv(DATA_DIR / ".env", override=True)

PREVIEW_DIR = DATA_DIR / "previews"
STORE_PATH = DATA_DIR / "photopick.json"

DATA_DIR.mkdir(parents=True, exist_ok=True)
PREVIEW_DIR.mkdir(parents=True, exist_ok=True)

GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
GEMINI_MODEL = os.environ.get("GEMINI_MODEL", "gemini-flash-latest")

# hashing per file, run concurrently via a thread pool
IMPORT_CONCURRENCY = int(os.environ.get("IMPORT_CONCURRENCY", "2"))

# How many camera originals may be decoded into previews at once.
# Each 20–40MB JPEG expands to ~100MB+ in RAM; keep this low.
PREVIEW_GEN_CONCURRENCY = int(os.environ.get("PREVIEW_GEN_CONCURRENCY", "1"))

# Grid thumbs — keep modest so decode/resize stays cheap
PREVIEW_MAX_WIDTH = int(os.environ.get("PREVIEW_MAX_WIDTH", "1280"))
PREVIEW_JPEG_QUALITY = int(os.environ.get("PREVIEW_JPEG_QUALITY", "80"))

JPEG_EXTENSIONS = {".jpg", ".jpeg", ".png"}
# iPhone / Apple photos (decoded via pillow-heif → JPEG preview for UI).
HEIC_EXTENSIONS = {".heic", ".heif"}
# Common camera RAW containers. Previews are JPEG extracts/demosaics stored
# under data/previews/<project_id>/ — never written into the user's photo folder.
RAW_EXTENSIONS = {
    ".arw",   # Sony
    ".cr2", ".cr3",  # Canon
    ".nef", ".nrw",  # Nikon
    ".raf",   # Fujifilm
    ".rw2",   # Panasonic
    ".orf",   # Olympus
    ".dng",   # Adobe / phones
    ".pef",   # Pentax
    ".srw",   # Samsung
}
# Non-RAW stills that we decode with Pillow (incl. HEIC).
RASTER_EXTENSIONS = JPEG_EXTENSIONS | HEIC_EXTENSIONS
SUPPORTED_EXTENSIONS = RASTER_EXTENSIONS | RAW_EXTENSIONS

# Full-resolution RAW demosaic for export is memory-heavy; keep this low.
EXPORT_CONCURRENCY = int(os.environ.get("EXPORT_CONCURRENCY", "2"))

ANALYZE_CONCURRENCY = int(os.environ.get("ANALYZE_CONCURRENCY", "2"))
ANALYZE_MAX_RETRIES = 6

# Gemini free-tier is rate-limited per minute per model (we've observed as
# low as 5 RPM on gemini-3.6-flash). Pace requests to stay under this instead
# of just reacting to 429s after the fact. Override once you know your
# actual tier's limit (paid tiers are much higher).
GEMINI_RPM = int(os.environ.get("GEMINI_RPM", "4"))

LICENSE_API_BASE = os.environ.get("LICENSE_API_BASE", DEFAULT_LICENSE_API_BASE)
# Packaged .app must not use a loopback license server. Older builds copied a
# dev .env (LICENSE_API_BASE=http://127.0.0.1:8000) into Application Support;
# that broke activate / update checks for end users.
if _running_from_app_bundle() and _is_loopback_url(LICENSE_API_BASE):
    LICENSE_API_BASE = DEFAULT_LICENSE_API_BASE
    os.environ["LICENSE_API_BASE"] = DEFAULT_LICENSE_API_BASE



def app_version() -> str:
    version_file = PROJECT_ROOT / "VERSION"
    try:
        return version_file.read_text(encoding="utf-8").strip() or "0.0.0"
    except OSError:
        return "0.0.0"
