# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
from qgis import processing
import pygris
from qgis.core import QgsProject
from ..prepare import PopSynth
from .show_dialog import show_diag
from ..common_tools import layer_from_geodataframe


def popsynth(proj):

    gdf = pygris.counties(cb=True, resolution="20m").to_crs(epsg=4326)
    gdf = gdf[["geometry", "GEOID", "NAME", "STATE_NAME"]]

    counties = layer_from_geodataframe(gdf, "Polygon", "Counties", add_layer=True)

    if proj.open_mode:
        proj.load_layer_by_name("zone")
        zones = proj.layers["zone"][0]

        processing.run("qgis:selectbylocation", {"INPUT": counties, "PREDICATE": 0, "INTERSECT": zones, "METHOD": 0})

        QgsProject.instance().setCrs(zones.crs())
        zones.updateExtents()
        proj.iface.mapCanvas().setExtent(zones.extent())
        proj.iface.mapCanvas().refresh()
        proj.iface.mapCanvas().zoomToFullExtent()

    dlg2 = PopSynth(proj)
    show_diag(dlg2)
