import os 
from qgis.core import (
    QgsProject,
    QgsRasterLayer,
    QgsCoordinateReferenceSystem,
)

from qgis.PyQt.QtWidgets import QMessageBox
from qgis import utils as qgis_utils


EPSG_3857 = QgsCoordinateReferenceSystem("EPSG:3857")


def start_setup(iface):
    project = QgsProject.instance()

    # --------------------------------------------------
    # Ensure project is saved
    # --------------------------------------------------
    if not project.fileName():
        QMessageBox.warning(
            iface.mainWindow(),
            "Project Not Saved",
            "Please save your QGIS project before running setup."
        )
        return

    # --------------------------------------------------
    # CRS check
    # --------------------------------------------------
    if project.crs().authid() != "EPSG:3857":
        fix = QMessageBox.question(
            iface.mainWindow(),
            "Project CRS",
            "Switch project CRS to EPSG:3857?",
            QMessageBox.Yes | QMessageBox.No
        )
        if fix == QMessageBox.Yes:
            project.setCrs(EPSG_3857)
            iface.mapCanvas().setDestinationCrs(EPSG_3857)
            iface.mapCanvas().refresh()

    # --------------------------------------------------
    # QuickMapServices check (non-fatal)
    # --------------------------------------------------
    if "quick_map_services" not in qgis_utils.plugins:
        QMessageBox.information(
            iface.mainWindow(),
            "Optional Plugin",
            "QuickMapServices is not installed.\n\n"
            "Basemap loading will still work, but QMS is recommended."
        )

    # --------------------------------------------------
    # Basemap prompt
    # --------------------------------------------------
    load = QMessageBox.question(
        iface.mainWindow(),
        "Basemap",
        "Load Esri World Imagery basemap?",
        QMessageBox.Yes | QMessageBox.No
    )

    if load == QMessageBox.Yes:
        uri = (
            "type=xyz&"
            "url=https://services.arcgisonline.com/ArcGIS/rest/services/"
            "World_Imagery/MapServer/tile/{z}/{y}/{x}"
        )
        rlayer = QgsRasterLayer(uri, "Esri World Imagery", "wms")
        if rlayer.isValid():
            QgsProject.instance().addMapLayer(rlayer)

    # --------------------------------------------------
    # Done
    # --------------------------------------------------
    QMessageBox.information(
        iface.mainWindow(),
        "Setup Complete",
        "Asphalt Intelligence setup is complete."
    )
