"""
Custom Security Policies for {{ service_name }}
Generated by ABI-Core scaffolding
"""

import os
import logging
from typing import Dict, Any, List
from datetime import datetime

logger = logging.getLogger(__name__)

class {{ service_class_name }}PolicyGenerator:
    """
    Custom policy generator for {{ service_name }}
    
    Extends ABI core policies with domain-specific security rules
    """
    
    def __init__(self):
        self.service_name = "{{ service_name }}"
        self.domain = "{{ domain | default('general') }}"
        
        # Custom policy configuration
        self.custom_rules = []
        self.risk_thresholds = {}
        
        logger.info(f"Initialized {{ service_class_name }}PolicyGenerator for domain: {self.domain}")
    
    def generate_custom_policies(self) -> str:
        """Generate custom OPA policies for {{ service_name }}"""
        
        timestamp = datetime.utcnow().isoformat()
        
        # Simple policy content without complex templating
        policy_content = '''# {{ service_name }} Custom Security Policies
# Generated at: ''' + timestamp + '''
# Domain: {{ domain | default('general') }}

package {{ service_name.lower().replace('-', '_') }}.custom

# Import core ABI policies
import data.abi.core

# Domain-specific agents
service_agents := {
    "{{ service_name.lower() }}_agent",
    "orchestrator",
    "planner"
}

# Domain-specific resources
service_resources := {
    "{{ domain | default('general') }}_data",
    "{{ service_name.lower() }}_config"
}

# Allow if core policies allow
allow if {
    data.abi.core.allow
    custom_rules_allow
}

# Custom rules
custom_rules_allow if {
    input.source_agent in service_agents
    input.resource_type in service_resources
}

# Custom audit log
custom_audit_log = {
    "service": "{{ service_name }}",
    "domain": "{{ domain | default('general') }}",
    "timestamp": time.now_ns()
}
'''
        
        return policy_content
    
    def write_policies(self, output_path: str) -> bool:
        """Write custom policies to file"""
        try:
            logger.info(f"Writing custom policies for {{ service_name }} to: {output_path}")
            
            # Generate custom policy content
            policy_content = self.generate_custom_policies()
            
            # Ensure output directory exists
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            
            # Write policy file
            with open(output_path, 'w') as f:
                f.write(policy_content)
            
            logger.info(f"Successfully wrote custom policies to: {output_path}")
            return True
            
        except Exception as e:
            logger.error(f"Error writing custom policies: {e}")
            return False

# Policy generator instance
policy_generator = {{ service_class_name }}PolicyGenerator()