"""SHIRE local voice privacy foundation.

This module is intentionally passive.

It does not open an audio device, start a recording, invoke PipeWire,
run speech recognition, verify a speaker, retain audio, or change input
devices. Hardware access remains disabled until a later milestone receives
separate preparation and application approval.
"""

from dataclasses import dataclass
from enum import Enum
import json
from pathlib import Path
from typing import Any, Dict


CONFIG_PATH = (
    Path(__file__).resolve().parent.parent
    / "config"
    / "voice_privacy.json"
)


class MicrophoneState(str, Enum):
    OFF = "OFF"
    READY = "READY"
    LISTENING = "LISTENING"
    PROCESSING = "PROCESSING"
    ERROR = "ERROR"


@dataclass(frozen=True)
class VoicePrivacySnapshot:
    state: str
    backend: str
    source_name: str
    hardware_name: str
    laptop_only: bool
    local_only: bool
    retain_audio: bool
    continuous_listening: bool
    wake_word_monitoring_enabled: bool
    wake_word_attention_is_non_authoritative: bool
    command_authority_requires_speaker_verification: bool
    microphone_access_enabled: bool
    speech_recognition_enabled: bool
    speaker_verification_enabled: bool
    speaker_verification_required: bool
    enrolled_speaker_count: int
    error: str


class VoicePrivacyFoundation:
    """Read-only policy and state foundation for future local voice work."""

    def __init__(self, config_path: Path = CONFIG_PATH) -> None:
        self.config_path = Path(config_path)
        self._state = MicrophoneState.OFF
        self._error = ""
        self._config: Dict[str, Any] = {}

        self._load_config()

    def _load_config(self) -> None:
        try:
            data = json.loads(
                self.config_path.read_text(encoding="utf-8")
            )

            device = data["device"]
            privacy = data["privacy"]
            implementation = data["implementation"]

            if implementation["microphone_access_enabled"] is not False:
                raise ValueError(
                    "Microphone access must remain disabled in "
                    "SHIRE-VOICE-0001A."
                )

            if privacy["retain_audio"] is not False:
                raise ValueError(
                    "Audio retention must remain disabled."
                )

            if privacy["continuous_listening"] is not False:
                raise ValueError(
                    "Continuous listening must remain disabled."
                )

            if privacy["local_only"] is not True:
                raise ValueError(
                    "Voice processing must remain local-only."
                )

            if not isinstance(
                privacy.get("enrolled_speakers"),
                list,
            ):
                raise ValueError(
                    "enrolled_speakers must be a list."
                )

            self._config = data
            self._state = MicrophoneState.OFF
            self._error = ""

        except Exception as exc:
            self._config = {}
            self._state = MicrophoneState.ERROR
            self._error = str(exc)

    def snapshot(self) -> VoicePrivacySnapshot:
        device = self._config.get("device", {})
        privacy = self._config.get("privacy", {})
        implementation = self._config.get("implementation", {})
        enrolled = privacy.get("enrolled_speakers", [])

        return VoicePrivacySnapshot(
            state=self._state.value,
            backend=str(device.get("backend", "unknown")),
            source_name=str(device.get("source_name", "unknown")),
            hardware_name=str(device.get("hardware_name", "unknown")),
            laptop_only=bool(device.get("laptop_only", False)),
            local_only=bool(privacy.get("local_only", False)),
            retain_audio=bool(privacy.get("retain_audio", False)),
            continuous_listening=bool(
                privacy.get("continuous_listening", False)
            ),
            wake_word_monitoring_enabled=bool(
                implementation.get(
                    "wake_word_monitoring_enabled",
                    False,
                )
            ),
            wake_word_attention_is_non_authoritative=bool(
                privacy.get(
                    "wake_word_attention_is_non_authoritative",
                    False,
                )
            ),
            command_authority_requires_speaker_verification=bool(
                privacy.get(
                    "command_authority_requires_speaker_verification",
                    True,
                )
            ),
            microphone_access_enabled=bool(
                implementation.get(
                    "microphone_access_enabled",
                    False,
                )
            ),
            speech_recognition_enabled=bool(
                implementation.get(
                    "speech_recognition_enabled",
                    False,
                )
            ),
            speaker_verification_enabled=bool(
                implementation.get(
                    "speaker_verification_enabled",
                    False,
                )
            ),
            speaker_verification_required=bool(
                privacy.get(
                    "speaker_verification_required",
                    True,
                )
            ),
            enrolled_speaker_count=(
                len(enrolled)
                if isinstance(enrolled, list)
                else 0
            ),
            error=self._error,
        )


voice_privacy_foundation = VoicePrivacyFoundation()
