# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later

"""GeoClue2-based location service for Linux."""

import logging

log = logging.getLogger(__name__)


def get_location_linux(callback):
    """Get current location using GeoClue2.

    Args:
        callback: Function to call with (latitude, longitude, error).
                  If successful, error is None. If failed, lat/lon are None.
    """
    try:
        import gi
        gi.require_version("Geoclue", "2.0")
        from gi.repository import Geoclue

        def _on_ready(source, result, *args):
            try:
                geoclue = Geoclue.Simple.new_finish(result)
                loc = geoclue.get_location()
                lat = loc.get_property("latitude")
                lon = loc.get_property("longitude")
                log.info(f"Location obtained: {lat}, {lon}")
                callback(lat, lon, None)
            except Exception as e:
                log.error(f"Failed to get location: {e}")
                callback(None, None, str(e))

        Geoclue.Simple.new(
            "page.codeberg.sesivany.Meshy",
            Geoclue.AccuracyLevel.EXACT,
            None,
            _on_ready,
        )

    except Exception as e:
        log.error(f"Failed to initialize GeoClue: {e}")
        callback(None, None, str(e))
