import requests
import base64
import mimetypes
from pathlib import Path
from html import escape
from .config_manager import ConfigManager


class OdooAPI:
    def __init__(self, config: ConfigManager, logger):
        self.config = config
        self.logger = logger
        self.mock_mode = self.config.getboolean("APP", "mock_mode", fallback=False)
        self.base_url = self.config.get("ODOO", "odoo_url")
        self.db = self.config.get("ODOO", "odoo_db")
        self.username = self.config.get("ODOO", "odoo_username")
        self.api_key = self.config.get("ODOO", "odoo_api_key")
        self.helpdesk_model = self.config.get("ODOO", "helpdesk_model", fallback="helpdesk.ticket")
        self.team_id = self.config.getint("ODOO", "default_team_id", fallback=0)
        self.stage_id = self.config.getint("ODOO", "default_stage_id", fallback=0)
        self.uid = None
        self._fields_cache = {}

    def create_helpdesk_ticket(self, title, description, priority, requester=None, team_id=0, team_name="", attachments=None):
        if self.mock_mode:
            self.logger.info(f"MOCK_MODE: creation de ticket Odoo simulee: {title}")
            return {"id": 9999}

        if not self.base_url or not self.db or not self.username or not self.api_key:
            raise ValueError("La configuration Odoo est incomplete")

        endpoint = self.base_url.rstrip("/") + "/jsonrpc"
        headers = {"Content-Type": "application/json"}
        uid = self._authenticate(endpoint, headers)
        values = {
            "name": title,
            "description": description,
            "priority": str(priority),
        }
        requester = requester or {}
        try:
            partner_id = self._find_or_create_partner(uid, requester)
            if partner_id and self._field_exists(uid, self.helpdesk_model, "partner_id"):
                values["partner_id"] = partner_id
        except Exception as exc:
            self.logger.error(f"Association contact Odoo ignoree: {exc}")
        if requester.get("name") and self._field_exists(uid, self.helpdesk_model, "partner_name"):
            values["partner_name"] = requester["name"]
        if requester.get("email") and self._field_exists(uid, self.helpdesk_model, "partner_email"):
            values["partner_email"] = requester["email"]
        if requester.get("email") and self._field_exists(uid, self.helpdesk_model, "email_from"):
            values["email_from"] = requester["email"]
        if requester.get("phone") and self._field_exists(uid, self.helpdesk_model, "partner_phone"):
            values["partner_phone"] = requester["phone"]
        selected_team_id = team_id or self._find_helpdesk_team_id(uid, team_name) or self.team_id
        if selected_team_id > 0:
            values["team_id"] = selected_team_id
        if self.stage_id > 0:
            values["stage_id"] = self.stage_id

        payload = {
            "jsonrpc": "2.0",
            "method": "call",
            "params": {
                "service": "object",
                "method": "execute_kw",
                "args": [
                    self.db,
                    uid,
                    self.api_key,
                    self.helpdesk_model,
                    "create",
                    [values],
                ],
                "kwargs": {},
            },
            "id": 1,
        }
        try:
            data = self._post_json(endpoint, headers, payload)
            if data.get("error"):
                error = data["error"]
                error_message = error.get("data", {}).get("message") or error.get("message", "Erreur Odoo inconnue")
                self.logger.error(f"Odoo API error: {error_message}")
                raise RuntimeError(error_message)
            self.logger.info("Ticket Odoo cree")
            ticket_id = data.get("result")
            self._post_attachment_notes(uid, ticket_id, attachments or [])
            return {"id": ticket_id}
        except requests.RequestException as exc:
            self.logger.error(f"Erreur API Odoo: {exc}")
            raise

    def append_to_ticket(self, ticket_id, note, attachments=None):
        if self.mock_mode:
            self.logger.info(f"MOCK_MODE: ajout au ticket Odoo simule: {ticket_id}")
            return True

        endpoint = self.base_url.rstrip("/") + "/jsonrpc"
        headers = {"Content-Type": "application/json"}
        uid = self._authenticate(endpoint, headers)
        ticket_id = int(ticket_id)
        current = self._execute_kw(uid, self.helpdesk_model, "read", [[ticket_id], ["description"]])
        current_description = ""
        if current:
            current_description = current[0].get("description") or ""
        new_description = f"{current_description}\n{note}".strip()
        self._execute_kw(uid, self.helpdesk_model, "write", [[ticket_id], {"description": new_description}])
        self._post_attachment_notes(uid, ticket_id, attachments or [])
        self.logger.info(f"Message ajoute au ticket Odoo {ticket_id}")
        return True

    def _post_attachment_notes(self, uid, ticket_id, attachments):
        for attachment in attachments:
            attachment_id = self._create_attachment(uid, ticket_id, attachment)
            if not attachment_id:
                continue
            body = (
                "<p>Photo envoyee par le client via Telegram.</p>"
                f'<p><img src="/web/image/ir.attachment/{attachment_id}/datas" '
                'style="max-width: 700px; height: auto;" /></p>'
            )
            if attachment.get("url"):
                safe_url = escape(attachment["url"], quote=True)
                body += f'<p><a href="{safe_url}" target="_blank">Ouvrir la photo</a></p>'
            try:
                self._execute_kw(
                    uid,
                    self.helpdesk_model,
                    "message_post",
                    [[int(ticket_id)]],
                    {
                        "body": body,
                        "message_type": "comment",
                        "subtype_xmlid": "mail.mt_note",
                        "attachment_ids": [attachment_id],
                    },
                )
                self.logger.info(f"Note Odoo creee avec photo pour ticket {ticket_id}")
            except Exception as exc:
                self.logger.error(f"Echec creation note Odoo avec photo: {exc}")

    def _create_attachment(self, uid, ticket_id, attachment):
        path = attachment.get("path")
        if not path:
            return None
        file_path = Path(path)
        if not file_path.exists():
            self.logger.error(f"Piece jointe introuvable: {file_path}")
            return None
        try:
            encoded = base64.b64encode(file_path.read_bytes()).decode("ascii")
            values = {
                "name": attachment.get("name") or file_path.name,
                "datas": encoded,
                "res_model": self.helpdesk_model,
                "res_id": int(ticket_id),
                "type": "binary",
            }
            mimetype = mimetypes.guess_type(file_path.name)[0]
            if mimetype:
                values["mimetype"] = mimetype
            attachment_id = self._execute_kw(uid, "ir.attachment", "create", [[values]])
            self.logger.info(f"Piece jointe Odoo creee pour ticket {ticket_id}: {file_path.name}")
            return attachment_id
        except Exception as exc:
            self.logger.error(f"Echec creation piece jointe Odoo: {exc}")
            return None

    def is_ticket_open(self, ticket_id):
        if self.mock_mode:
            return True

        endpoint = self.base_url.rstrip("/") + "/jsonrpc"
        headers = {"Content-Type": "application/json"}
        uid = self._authenticate(endpoint, headers)
        ticket_id = int(ticket_id)
        fields = ["stage_id"]
        if self._field_exists(uid, self.helpdesk_model, "active"):
            fields.append("active")
        if self._field_exists(uid, self.helpdesk_model, "close_date"):
            fields.append("close_date")

        ticket = self._execute_kw(uid, self.helpdesk_model, "read", [[ticket_id], fields])
        if not ticket:
            return False
        ticket = ticket[0]
        if ticket.get("active") is False:
            return False
        if ticket.get("close_date"):
            return False

        stage = ticket.get("stage_id")
        if not stage:
            return True
        stage_id = stage[0] if isinstance(stage, list) else stage
        stage_name = stage[1] if isinstance(stage, list) and len(stage) > 1 else ""

        try:
            stage_fields = ["name"]
            stage_model = "helpdesk.stage"
            if self._field_exists(uid, stage_model, "fold"):
                stage_fields.append("fold")
            stage_record = self._execute_kw(uid, stage_model, "read", [[stage_id], stage_fields])
            if stage_record:
                stage_data = stage_record[0]
                stage_name = stage_data.get("name") or stage_name
                if stage_data.get("fold") is True:
                    return False
        except Exception as exc:
            self.logger.error(f"Verification etape ticket Odoo ignoree: {exc}")

        closed_names = ["clos", "ferme", "fermé", "resolu", "résolu", "done", "closed", "annule", "annulé"]
        normalized_stage = (stage_name or "").lower()
        return not any(name in normalized_stage for name in closed_names)

    def is_ticket_in_team(self, ticket_id, team_id=0, team_name=""):
        if self.mock_mode:
            return True

        endpoint = self.base_url.rstrip("/") + "/jsonrpc"
        headers = {"Content-Type": "application/json"}
        uid = self._authenticate(endpoint, headers)
        ticket_id = int(ticket_id)

        if not self._field_exists(uid, self.helpdesk_model, "team_id"):
            return True

        expected_team_id = team_id or self._find_helpdesk_team_id(uid, team_name)
        if not expected_team_id and not team_name:
            return True

        ticket = self._execute_kw(uid, self.helpdesk_model, "read", [[ticket_id], ["team_id"]])
        if not ticket:
            return False
        current_team = ticket[0].get("team_id")
        if not current_team:
            return False

        current_team_id = current_team[0] if isinstance(current_team, list) else current_team
        current_team_name = current_team[1] if isinstance(current_team, list) and len(current_team) > 1 else ""

        if expected_team_id:
            return int(current_team_id) == int(expected_team_id)
        return team_name.lower() in (current_team_name or "").lower()

    def _find_or_create_partner(self, uid, requester):
        name = (requester.get("name") or "Client SAV").strip()
        phone = (requester.get("phone") or "").strip()
        email = (requester.get("email") or "").strip()
        telegram_chat_id = (requester.get("telegram_chat_id") or "").strip()

        partner_fields = self._get_model_fields(uid, "res.partner")
        domain = []
        if email:
            domain = [["email", "=", email]]
        elif phone:
            phone_domain = []
            if "phone" in partner_fields:
                phone_domain.append(["phone", "=", phone])
            if "mobile" in partner_fields:
                phone_domain.append(["mobile", "=", phone])
            if len(phone_domain) == 2:
                domain = ["|", phone_domain[0], phone_domain[1]]
            elif len(phone_domain) == 1:
                domain = [phone_domain[0]]
        elif name and name != "Client SAV":
            domain = [["name", "=", name]]

        if domain:
            found = self._execute_kw(uid, "res.partner", "search_read", [domain], {"fields": ["id"], "limit": 1})
            if found:
                partner_id = found[0]["id"]
                self._update_partner(uid, partner_id, phone, email, telegram_chat_id)
                return partner_id

        values = {"name": name}
        if phone and "phone" in partner_fields:
            values["phone"] = phone
        if phone and "mobile" in partner_fields:
            values["mobile"] = phone
        if email and "email" in partner_fields:
            values["email"] = email
        if telegram_chat_id and "comment" in partner_fields:
            values["comment"] = f"Telegram chat ID: {telegram_chat_id}"
        return self._execute_kw(uid, "res.partner", "create", [[values]])

    def _update_partner(self, uid, partner_id, phone, email, telegram_chat_id):
        partner_fields = self._get_model_fields(uid, "res.partner")
        values = {}
        if phone and "phone" in partner_fields:
            values["phone"] = phone
        if phone and "mobile" in partner_fields:
            values["mobile"] = phone
        if email and "email" in partner_fields:
            values["email"] = email
        if telegram_chat_id and "comment" in partner_fields:
            values["comment"] = f"Telegram chat ID: {telegram_chat_id}"
        if values:
            self._execute_kw(uid, "res.partner", "write", [[partner_id], values])

    def _find_helpdesk_team_id(self, uid, team_name):
        team_name = (team_name or "").strip()
        if not team_name:
            return 0
        try:
            found = self._execute_kw(
                uid,
                "helpdesk.team",
                "search_read",
                [[["name", "ilike", team_name]]],
                {"fields": ["id", "name"], "limit": 1},
            )
            if found:
                self.logger.info(f"Equipe Odoo trouvee pour '{team_name}': {found[0].get('name')} ({found[0].get('id')})")
                return found[0]["id"]
        except Exception as exc:
            self.logger.error(f"Recherche equipe Odoo ignoree pour '{team_name}': {exc}")
        return 0

    def _field_exists(self, uid, model, field_name):
        fields = self._get_model_fields(uid, model)
        return field_name in fields

    def _get_model_fields(self, uid, model):
        if model not in self._fields_cache:
            self._fields_cache[model] = self._execute_kw(uid, model, "fields_get", [], {"attributes": ["type"]})
        return self._fields_cache[model]

    def _execute_kw(self, uid, model, method, args=None, kwargs=None):
        endpoint = self.base_url.rstrip("/") + "/jsonrpc"
        headers = {"Content-Type": "application/json"}
        payload = {
            "jsonrpc": "2.0",
            "method": "call",
            "params": {
                "service": "object",
                "method": "execute_kw",
                "args": [
                    self.db,
                    uid,
                    self.api_key,
                    model,
                    method,
                    args or [],
                    kwargs or {},
                ],
            },
            "id": 1,
        }
        data = self._post_json(endpoint, headers, payload)
        if data.get("error"):
            error = data["error"]
            error_message = error.get("data", {}).get("message") or error.get("message", "Erreur Odoo inconnue")
            self.logger.error(f"Odoo API error on {model}.{method}: {error_message}")
            raise RuntimeError(error_message)
        return data.get("result")

    def _authenticate(self, endpoint, headers):
        if self.uid:
            return self.uid

        payload = {
            "jsonrpc": "2.0",
            "method": "call",
            "params": {
                "service": "common",
                "method": "login",
                "args": [self.db, self.username, self.api_key],
            },
            "id": 1,
        }
        try:
            data = self._post_json(endpoint, headers, payload)
            if data.get("error"):
                error = data["error"]
                error_message = error.get("data", {}).get("message") or error.get("message", "Erreur authentification Odoo")
                self.logger.error(f"Odoo auth error: {error_message}")
                raise RuntimeError(error_message)
            uid = data.get("result")
            if not uid:
                raise RuntimeError("Authentification Odoo refusee")
            self.uid = uid
            return uid
        except requests.RequestException as exc:
            self.logger.error(f"Erreur authentification Odoo: {exc}")
            raise

    def _post_json(self, endpoint, headers, payload):
        response = requests.post(endpoint, json=payload, headers=headers, timeout=15)
        response.raise_for_status()
        return response.json()
