# /***************************************************************************
#  SecInterp
#                                  A QGIS plugin
#  Data extraction for geological interpretation.
#  Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/.
#                               -------------------
#         begin                : 2025-11-15
#         git sha              : $Format:%H$
#         copyright            : (C) 2025 by Juan M Bernales
#         email                : juanbernales@gmail.com
#  ***************************************************************************/
#
# /***************************************************************************
#  *                                                                         *
#  *   This program is free software; you can redistribute it and/or modify  *
#  *   it under the terms of the GNU General Public License as published by  *
#  *   the Free Software Foundation; either version 2 of the License, or     *
#  *   (at your option) any later version.                                   *
#  *                                                                         *
#  ***************************************************************************/

"""Utility for reading plugin metadata from metadata.txt.

This module provides functionality to read plugin information from the
standard QGIS metadata.txt file, ensuring a single source of truth for
plugin version, author, and other metadata.
"""

from __future__ import annotations

from configparser import ConfigParser
from contextlib import suppress
from pathlib import Path
from typing import TYPE_CHECKING

from sec_interp.logger_config import get_logger

if TYPE_CHECKING:
    pass

logger = get_logger(__name__)

# Cache for metadata to avoid repeated file reads
_metadata_cache: dict[str, str] | None = None


def read_plugin_metadata() -> dict[str, str]:
    """Read plugin metadata from metadata.txt.

    Reads the standard QGIS metadata.txt file and extracts key information
    about the plugin. Results are cached to avoid repeated file I/O.

    Returns:
        Dict[str, str]: Dictionary containing plugin metadata with keys:
            - name: Plugin name
            - version: Plugin version
            - author: Plugin author
            - email: Contact email
            - description: Short description
            - homepage: Documentation URL (if available)
            - repository: Source code URL (if available)

    Raises:
        FileNotFoundError: If metadata.txt cannot be found
        ValueError: If required fields (name, version, author, email) are missing

    Example:
        >>> metadata = read_plugin_metadata()
        >>> print(f"{metadata['name']} v{metadata['version']}")
        Sec Interp v2.9.0

    """
    global _metadata_cache

    # Return cached metadata if available
    if _metadata_cache is not None:
        return _metadata_cache

    # Locate metadata.txt (should be in project root)
    # This file is in core/utils/, so we need to go up 2 levels
    metadata_path = Path(__file__).parent.parent.parent / "metadata.txt"

    if not metadata_path.exists():
        msg = f"metadata.txt not found at {metadata_path}"
        logger.error(msg)
        raise FileNotFoundError(msg)

    # Parse metadata.txt using ConfigParser
    parser = ConfigParser()
    try:
        parser.read(metadata_path, encoding="utf-8")
    except Exception as e:
        msg = f"Failed to parse metadata.txt: {e}"
        logger.exception(msg)
        raise ValueError(msg) from e

    # Extract required fields
    required_fields = ["name", "version", "author", "email"]
    metadata = {}

    for field in required_fields:
        try:
            metadata[field] = parser.get("general", field)
        except Exception as e:
            msg = f"Required field '{field}' missing in metadata.txt"
            logger.exception(msg)
            raise ValueError(msg) from e

    # Extract optional fields
    optional_fields = ["description", "homepage", "repository", "about"]
    for field in optional_fields:
        with suppress(Exception):
            metadata[field] = parser.get("general", field)

    # Cache the metadata
    _metadata_cache = metadata

    logger.debug(f"Loaded plugin metadata: {metadata['name']} v{metadata['version']}")
    return metadata


def clear_metadata_cache() -> None:
    """Clear the metadata cache.

    Useful for testing or when metadata.txt is updated at runtime.
    """
    global _metadata_cache
    _metadata_cache = None
    logger.debug("Metadata cache cleared")
