"""
AgentGuard Disclosure Manager

Implements transparency obligations per EU AI Act Article 50.
Ensures users are informed when interacting with an AI system.
"""

from __future__ import annotations

import json
from datetime import datetime, timezone
from typing import Any

from .config import ContentLabel, DisclosureMethod


class DisclosureManager:
    """
    Manages AI interaction disclosure and content labeling.

    Article 50(1): Users must be informed they are interacting with AI.
    Article 50(2): AI-generated content must be machine-readable marked.
    """

    def __init__(
        self,
        system_name: str,
        provider_name: str,
        method: DisclosureMethod = DisclosureMethod.PREPEND,
        disclosure_text: str | None = None,
    ):
        self.system_name = system_name
        self.provider_name = provider_name
        self.method = method
        self._disclosure_text = disclosure_text or (
            f"🤖 This response was generated by an AI system ({system_name}) "
            f"operated by {provider_name}."
        )

    def apply_disclosure(
        self,
        response_text: str,
        interaction_id: str | None = None,
    ) -> str | dict[str, Any]:
        """
        Apply AI disclosure to a response.

        For PREPEND: returns modified string with disclosure prepended.
        For METADATA: returns dict with response and metadata.
        """
        if self.method == DisclosureMethod.PREPEND:
            return f"{self._disclosure_text}\n\n{response_text}"

        elif self.method == DisclosureMethod.METADATA:
            return {
                "response": response_text,
                "ai_disclosure": {
                    "is_ai_generated": True,
                    "system_name": self.system_name,
                    "provider_name": self.provider_name,
                    "interaction_id": interaction_id,
                    "timestamp": datetime.now(timezone.utc).isoformat(),
                },
            }

        return response_text

    def get_http_headers(self, interaction_id: str | None = None) -> dict[str, str]:
        """
        Get HTTP headers for API-based disclosure (Article 50).

        These headers should be included in API responses so downstream
        consumers know the content is AI-generated.
        """
        return {
            "X-AI-Generated": "true",
            "X-AI-System": self.system_name,
            "X-AI-Provider": self.provider_name,
            "X-AI-Interaction-ID": interaction_id or "",
            "X-AI-Timestamp": datetime.now(timezone.utc).isoformat(),
            "X-AI-Act-Compliant": "true",
        }

    def create_content_label(
        self,
        model: str | None = None,
        interaction_id: str | None = None,
    ) -> ContentLabel:
        """
        Create a machine-readable content label (Article 50(2)).

        This label should be embedded in or attached to AI-generated content
        to enable detection of artificial generation.
        """
        return ContentLabel(
            generator=self.system_name,
            model=model,
            provider=self.provider_name,
            interaction_id=interaction_id,
        )

    def to_c2pa_assertion(
        self,
        model: str | None = None,
        interaction_id: str | None = None,
    ) -> dict[str, Any]:
        """
        Generate a C2PA-style assertion for content provenance.

        C2PA (Coalition for Content Provenance and Authenticity) is the
        emerging standard for content labeling referenced in the EU AI Act
        Code of Practice on Transparency.
        """
        return {
            "dc:title": f"AI-generated content by {self.system_name}",
            "dc:creator": self.provider_name,
            "ai_info": {
                "ai_generated": True,
                "ai_system": self.system_name,
                "ai_model": model or "unknown",
                "ai_provider": self.provider_name,
            },
            "claim_generator_info": {
                "name": "AgentGuard",
                "version": "0.1.0",
            },
            "interaction_ref": interaction_id,
            "timestamp": datetime.now(timezone.utc).isoformat(),
        }

    def embed_text_label(self, text: str, model: str | None = None) -> str:
        """
        Embed a machine-readable label in text content.

        Adds an invisible Unicode-based marker and a visible footer
        for AI-generated text, as required by Article 50(2).
        """
        label = self.create_content_label(model=model)
        label_json = json.dumps(
            {
                "ai_generated": True,
                "system": label.generator,
                "provider": label.provider,
                "model": label.model,
                "timestamp": label.timestamp.isoformat(),
            }
        )
        # Embed as HTML comment (for web content) or as metadata footer
        marker = f"\n\n<!-- agentguard:ai-generated {label_json} -->"
        return text + marker
