"""Private QgsProject for Beaver processor.

Inside QGIS Desktop, ``QgsProject.instance()`` is the *user's open project* —
reading, clearing, or writing it from a plugin would destroy their work. All
Beaver processor code therefore operates on a dedicated project object that
holds the bundled ``master_project.qgz`` (layers, styles, print layouts).

``core_project()``   — lazily loads and returns the shared private project.
``reload_core_project()`` — clears and re-reads it (the exporter calls this at
the start of every build to reset layer/layout state, exactly as the parent
app did with the singleton).

In standalone mode this is functionally identical to the old singleton usage;
in plugin mode it is what keeps the host project untouched.
"""

import logging

from qgis.core import QgsProject

from .config import QGIS_PROJECT_PATH

logger = logging.getLogger(__name__)

_PROJECT = None


def core_project() -> QgsProject:
    """Return the private project, loading the bundled .qgz on first use."""
    global _PROJECT
    if _PROJECT is None:
        _PROJECT = QgsProject()
        if not _PROJECT.read(QGIS_PROJECT_PATH):
            logger.error(f"Could not load bundled project: {QGIS_PROJECT_PATH}")
    return _PROJECT


def reload_core_project() -> QgsProject:
    """Clear and re-read the private project (fresh state for a new build)."""
    proj = core_project()
    proj.clear()
    if not proj.read(QGIS_PROJECT_PATH):
        raise Exception(f"Failed to load QGIS project from {QGIS_PROJECT_PATH}")
    return proj
