import os
import json
import base64
from cryptography.hazmat.primitives.asymmetric import ed25519
from cryptography.hazmat.primitives import serialization

class CryptoOriginSkill:
    """
    Implements P1: Cryptographic Validation.
    Signs AI-generated content to prove its origin.
    """
    def __init__(self, key_path="E:/genesis-system/config/genesis_gate_keys"):
        self.key_path = key_path
        self.private_key = None
        self.public_key = None
        self._ensure_keys()

    def _ensure_keys(self):
        priv_file = os.path.join(self.key_path, "gate1.priv")
        pub_file = os.path.join(self.key_path, "gate1.pub")

        if not os.path.exists(self.key_path):
            os.makedirs(self.key_path)

        if os.path.exists(priv_file):
            with open(priv_file, "rb") as f:
                self.private_key = ed25519.Ed25519PrivateKey.from_private_bytes(f.read())
        else:
            self.private_key = ed25519.Ed25519PrivateKey.generate()
            with open(priv_file, "wb") as f:
                f.write(self.private_key.private_bytes(
                    encoding=serialization.Encoding.Raw,
                    format=serialization.PrivateFormat.Raw,
                    encryption_algorithm=serialization.NoEncryption()
                ))

        self.public_key = self.private_key.public_key()
        if not os.path.exists(pub_file):
            with open(pub_file, "wb") as f:
                f.write(self.public_key.public_bytes(
                    encoding=serialization.Encoding.Raw,
                    format=serialization.PublicFormat.Raw
                ))

    def sign_content(self, content: str) -> str:
        """Signs text content and returns a base64 signature."""
        data = content.encode('utf-8')
        signature = self.private_key.sign(data)
        return base64.b64encode(signature).decode('utf-8')

    def verify_signature(self, content: str, signature_b64: str) -> bool:
        """Verifies a signature against content using the public key."""
        try:
            signature = base64.b64decode(signature_b64)
            self.public_key.verify(signature, content.encode('utf-8'))
            return True
        except Exception:
            return False

    def wrap_content(self, content: str) -> dict:
        """Wraps content with its cryptographic metadata."""
        signature = self.sign_content(content)
        return {
            "content": content,
            "verification": {
                "gate": "GATE1_ORIGIN",
                "patent": "P1",
                "signature": signature,
                "algorithm": "Ed25519"
            }
        }

if __name__ == "__main__":
    skill = CryptoOriginSkill()
    test_msg = "Genesis Autonomous Action: Initializing Pulse."
    wrapped = skill.wrap_content(test_msg)
    print(json.dumps(wrapped, indent=2))
    
    is_valid = skill.verify_signature(wrapped["content"], wrapped["verification"]["signature"])
    print(f"Verification: {'SUCCESS' if is_valid else 'FAILED'}")
