from services.odoo_services import OdooService
import os
from dotenv import load_dotenv
import logging

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
BASE_URL = os.getenv('BASE_URL')

class GetSurveyQuestionsService:

    @staticmethod
    def get_survey_questions_service(survey_id):
        if not survey_id:
            logging.error("Survey ID is missing.")
            return None

        logging.info(f"Fetching survey with ID: {survey_id}")
        survey = OdooService.search('survey.survey', [[['id', '=', survey_id], ['survey_type', '=', 'survey']]])
        logging.debug(f"Survey search result: {survey}")

        survey_details = OdooService.readAll('survey.survey', survey)
        logging.debug(f"Survey details fetched: {survey_details}")

        if not survey_details:
            logging.warning(f"No survey found for ID: {survey_id}")
            return None

        survey_detail = survey_details[0]
        question_ids = survey_detail.get('question_ids', [])
        if not question_ids:
            logging.warning(f"No questions found for survey ID: {survey_id}")
            return []

        logging.info(f"Fetching questions for survey ID: {survey_id}")
        questions_by_lang = {}
        for lang_code in ['en_US', 'si_LK', 'tn_LK']:
            questions = OdooService.readAll('survey.question', question_ids, context={'lang': lang_code})
            questions_by_lang[lang_code] = {q['id']: q for q in questions}

        logging.info("Building section (page) map from question data.")
        section_map = {}
        for qid in question_ids:
            question = questions_by_lang['en_US'].get(qid, {})
            page_info = question.get('page_id', [])
            if page_info:
                section_id, section_title = page_info[0], page_info[1]
                section_map[section_id] = section_title

        sort_order = 1

        section_questions_map = {}

        for question_id in question_ids:
            question_en = questions_by_lang['en_US'].get(question_id, {})
            question_si = questions_by_lang['si_LK'].get(question_id, {})
            question_ta = questions_by_lang['tn_LK'].get(question_id, {})

            section_id = question_en.get('page_id', [None])[0]
            section_title = section_map.get(section_id, 'Default Section')
            question_type = question_en.get('question_type')

            # map Odoo types to display types
            if question_type == 'simple_choice':
                question_display_type = 'radio'
            elif question_type == 'multiple_choice':
                question_display_type = 'checkbox'
            elif question_type == 'matrix':
                question_display_type = 'matrix'
            elif question_type == 'numerical_box':
                question_display_type = 'numerical'
            elif question_type == 'char_box':
                question_display_type = 'single line text box'
            elif question_type == 'text_box':
                question_display_type = 'multiple line text box'
            elif question_type == 'date':
                question_display_type = 'date'
            elif question_type == 'datetime':
                question_display_type = 'datetime'
            elif question_type == 'scale':
                question_display_type = 'scale'
            else:
                question_display_type = question_type or 'unknown'

            # base question data (always created) — note the added 'question_id' field
            question_data = {
                'question_id': question_id,
                'question_en': question_en.get('title', ''),
                'question_si': question_si.get('title', ''),
                'question_ta': question_ta.get('title', ''),
                'question_type': question_display_type,
                'special_question_type': '',
                'selection_values': {},
                'metrix_values': {},
                # default conditional fields (will be overwritten if triggers exist)
                'is_conditional': False,
                'conditional_triggers': []
            }

            # populate selection_values for choice questions
            if question_type in ['simple_choice', 'multiple_choice']:
                answer_ids = question_en.get('suggested_answer_ids', []) or []
                answers_by_lang = {}
                for lang_code in ['en_US', 'si_LK', 'tn_LK']:
                    answers = OdooService.readAll('survey.question.answer', answer_ids, context={'lang': lang_code}) if answer_ids else []
                    answers_by_lang[lang_code] = [a.get('value', '') for a in answers]

                question_data['selection_values'] = {
                    'en': answers_by_lang['en_US'],
                    'si': answers_by_lang['si_LK'],
                    'ta': answers_by_lang['tn_LK']
                }

            # populate matrix values
            if question_type == 'matrix':
                row_ids = question_en.get('matrix_row_ids', []) or []
                col_ids = question_en.get('suggested_answer_ids', []) or []
                rows_by_lang = {}
                cols_by_lang = {}

                for lang_code in ['en_US', 'si_LK', 'tn_LK']:
                    rows = OdooService.readAll('survey.question.answer', row_ids, context={'lang': lang_code}) if row_ids else []
                    cols = OdooService.readAll('survey.question.answer', col_ids, context={'lang': lang_code}) if col_ids else []
                    rows_by_lang[lang_code] = [r.get('value', '') for r in rows]
                    cols_by_lang[lang_code] = [c.get('value', '') for c in cols]

                question_data['metrix_values'] = {
                    'Type': question_en.get('matrix_type', ''),
                    'Metrix_row_titles': {
                        'en': rows_by_lang['en_US'],
                        'si': rows_by_lang['si_LK'],
                        'ta': rows_by_lang['tn_LK']
                    },
                    'Metrix_column_headers': {
                        'en': cols_by_lang['en_US'],
                        'si': cols_by_lang['si_LK'],
                        'ta': cols_by_lang['tn_LK']
                    }
                }

            # --- conditional trigger extraction (only adds metadata; DOES NOT remove the question) ---
            trigger_answer_ids = question_en.get('triggering_answer_ids', []) or []
            if trigger_answer_ids:
                triggers_by_lang = {}
                for lang_code in ['en_US', 'si_LK', 'tn_LK']:
                    trigger_answers = OdooService.readAll(
                        'survey.question.answer',
                        trigger_answer_ids,
                        context={'lang': lang_code}
                    ) if trigger_answer_ids else []
                    triggers_by_lang[lang_code] = {a['id']: a.get('value', '') for a in trigger_answers}

                trigger_answers_en = OdooService.readAll(
                    'survey.question.answer',
                    trigger_answer_ids,
                    context={'lang': 'en_US'}
                ) if trigger_answer_ids else []

                conditional_triggers = []
                for a in trigger_answers_en:
                    source_q = a.get('question_id') or []
                    source_q_id = source_q[0] if len(source_q) > 0 else None
                    source_q_title = source_q[1] if len(source_q) > 1 else ''
 
                    conditional_triggers.append({
                        'answer_id': a.get('id'),
                        'answer_value_en': triggers_by_lang['en_US'].get(a.get('id')),
                        'answer_value_si': triggers_by_lang['si_LK'].get(a.get('id')),
                        'answer_value_ta': triggers_by_lang['tn_LK'].get(a.get('id')),
                        'source_question_id': source_q_id,
                        'source_question_title_en': source_q_title,
                    })

                question_data['is_conditional'] = True
                question_data['conditional_triggers'] = conditional_triggers
            # ======= end conditional extraction =======

            # append to section map
            if section_id not in section_questions_map:
                section_questions_map[section_id] = {
                    'sort_order': sort_order,
                    'question_group_id': section_id,
                    'question_group_name': section_title,
                    'questions': []
                }
                sort_order += 1

            section_questions_map[section_id]['questions'].append(question_data)

        logging.info("Finished processing all survey questions.")
        survey_questions_response = list(section_questions_map.values())
        logging.debug(f"Final survey questions response: {survey_questions_response}")
        return survey_questions_response


