"""Transparency manager -- coordinates privacy manifest, resource monitoring, and activity logging.

Provides the "Nothing to Hide" guarantee: every action LLMHosts takes
is visible and verifiable by the user.
"""

from __future__ import annotations

import logging
import os
import platform
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any

from pydantic import BaseModel

if TYPE_CHECKING:
    from llmhosts.config import LLMHostsConfig

logger = logging.getLogger(__name__)


class TransparencyConfig(BaseModel):
    """Transparency and privacy configuration."""

    privacy_manifest: bool = True
    resource_monitor: bool = True
    activity_log_retention_hours: int = 24


class TransparencyReport(BaseModel):
    """Current transparency status for dashboard display."""

    privacy_manifest_path: str
    manifest_generated: datetime
    telemetry_enabled: bool = False
    outbound_connections: list[dict[str, str]]
    local_storage_paths: list[dict[str, Any]]
    gpu_usage_policy: str
    process_info: dict[str, Any]


class TransparencyManager:
    """Manages all transparency features."""

    def __init__(self, config: TransparencyConfig, llmhosts_config: LLMHostsConfig | None = None) -> None:
        self.config = config
        self._llmhosts_config = llmhosts_config

    def generate_report(self) -> TransparencyReport:
        """Generate current transparency report."""
        from llmhosts.security.privacy_manifest import PrivacyManifest

        manifest = PrivacyManifest.generate(self._llmhosts_config)
        manifest_path = self._get_manifest_path()

        return TransparencyReport(
            privacy_manifest_path=str(manifest_path),
            manifest_generated=datetime.now(timezone.utc),
            telemetry_enabled=False,
            outbound_connections=manifest.network_connections,
            local_storage_paths=manifest.local_storage,
            gpu_usage_policy=manifest.gpu_usage.get("note", "LLM inference only"),
            process_info=self._get_process_info(),
        )

    def _get_manifest_path(self) -> Path:
        """Get the path where the privacy manifest is stored."""
        config_dir = Path.home() / ".config" / "llmhosts"
        config_dir.mkdir(parents=True, exist_ok=True)
        return config_dir / "privacy-manifest.json"

    @staticmethod
    def _get_process_info() -> dict[str, Any]:
        """Get current process information for transparency."""
        return {
            "pid": os.getpid(),
            "platform": platform.system(),
            "python_version": platform.python_version(),
            "working_directory": str(Path.cwd()),
        }

    async def write_manifest(self) -> Path:
        """Write privacy manifest to disk."""
        from llmhosts.security.privacy_manifest import PrivacyManifest

        manifest = PrivacyManifest.generate(self._llmhosts_config)
        path = self._get_manifest_path()
        path.write_text(manifest.to_json(), encoding="utf-8")
        logger.info("Privacy manifest written to %s", path)
        return path
