import datetime
from typing import Optional
from lar.node import BaseNode
from lar.state import GraphState

class SyntheticMarkerNode(BaseNode):
    """
    Injects a machine-readable watermark or visible disclaimer into generated content.
    Operationalizes Article 50(2) transparency obligations for synthetic content.
    """
    def __init__(self, 
                 input_key: str, 
                 output_key: Optional[str] = None,
                 marker_type: str = "VISIBLE", 
                 next_node: Optional[BaseNode] = None):
        """
        Args:
            input_key: The state key containing the content to mark.
            output_key: The state key to save marked content (defaults to overwriting input_key).
            marker_type: "VISIBLE" (text disclaimer) or "METADATA" (simulated C2PA manifest).
        """
        self.input_key = input_key
        self.output_key = output_key or input_key
        self.marker_type = marker_type.upper()
        self.next_node = next_node

    def execute(self, state: GraphState):
        content = state.get(self.input_key)
        if not content:
            return self.next_node

        timestamp = datetime.datetime.utcnow().isoformat()
        
        if self.marker_type == "VISIBLE":
            if isinstance(content, str):
                marked_content = f"{content}\n\n[Disclaimer: This content was generated by an AI system on {timestamp}.]"
            else:
                # If it's a dict, add a disclaimer field
                marked_content = content.copy() if isinstance(content, dict) else {"original": content}
                marked_content["_ai_disclaimer"] = f"Generated by AI on {timestamp}"
                
        elif self.marker_type == "METADATA":
            # Simulate a C2PA metadata wrapper
            marked_content = {
                "c2pa_manifest": {
                    "generator": "Lar Framework v1.5.1",
                    "timestamp": timestamp,
                    "assertion": "AI_GENERATED"
                },
                "content": content
            }
        else:
            marked_content = content
            
        print(f"  [SyntheticMarkerNode] Applied {self.marker_type} marking to '{self.input_key}'.")
        state.set(self.output_key, marked_content)
        
        return self.next_node
