import json
import logging
from odoo import http
from odoo.http import request

_logger = logging.getLogger(__name__)


class SeoContentController(http.Controller):

    @http.route('/web/seo-content/check-api', type='jsonrpc', auth='user')
    def check_api_connection(self):
        """Check if API connection is configured and working."""
        try:
            ICP = request.env['ir.config_parameter'].sudo()
            api_key = ICP.get_param('otoolkit_api_key', '')
            base_url = ICP.get_param('otoolkit.api.endpoint', '')

            if not api_key or not base_url:
                return {
                    'success': False,
                    'error': 'API not configured',
                    'configured': False,
                }

            return {
                'success': True,
                'configured': True,
                'endpoint': base_url,
            }
        except Exception as e:
            _logger.exception("API check error")
            return {
                'success': False,
                'error': str(e),
            }

    @http.route('/web/seo-content/get-templates', type='json', auth='user')
    def get_templates(self, content_type=None):
        """Get available templates for a content type."""
        domain = [('active', '=', True)]
        if content_type:
            domain.append(('content_type', '=', content_type))

        templates = request.env['otk.seo.template'].search_read(
            domain,
            ['name', 'content_type', 'description', 'default_tone',
             'default_word_count', 'include_images', 'default_image_count'],
            order='sequence, name'
        )

        return {
            'success': True,
            'templates': templates,
        }

    @http.route('/web/seo-content/get-languages', type='jsonrpc', auth='user')
    def get_languages(self):
        """Get available languages for content generation."""
        languages = request.env['res.lang'].search_read(
            [('active', '=', True)],
            ['code', 'name', 'iso_code'],
            order='name'
        )

        return {
            'success': True,
            'languages': languages,
        }

    @http.route('/web/seo-content/get-blogs', type='jsonrpc', auth='user')
    def get_blogs(self):
        """Get available blogs for publishing."""
        try:
            blogs = request.env['blog.blog'].search_read(
                [('active', '=', True)],
                ['name', 'subtitle'],
                order='name'
            )
            return {
                'success': True,
                'blogs': blogs,
            }
        except Exception:
            # website_blog not installed
            return {
                'success': True,
                'blogs': [],
                'warning': 'Website Blog module not installed',
            }
