# -*- coding: utf-8 -*-
import json
import logging

import requests
from requests.exceptions import RequestException

from odoo import api, fields, models

_logger = logging.getLogger(__name__)


class AccountAnalyticLine(models.Model):
    _inherit = 'account.analytic.line'
    _description = 'Timesheet / Analytic Line'

    notes_internal = fields.Text(
        string='Internal Notes',
        help='Internal notes not visible to clients.',
    )
    eit_billing_id = fields.Char(
        string='EIT Billing ID',
        readonly=True,
        copy=False,
        index=True,
        help='Identifier returned by the EIT billing API.',
    )
    convergence_time_id = fields.Char(
        string='Convergence ID',
        readonly=True,
        copy=False,
        index=True,
        help='Identifier returned by the Convergence time tracking API.',
    )
    time_in = fields.Float(
        string='Time In',
        help='Clock-in time (24h decimal, e.g. 9.5 = 09:30).',
    )
    time_out = fields.Float(
        string='Time Out',
        help='Clock-out time (24h decimal, e.g. 17.5 = 17:30).',
    )
    is_invoiced = fields.Boolean(
        string='Invoiced',
        default=False,
        index=True,
        copy=False,
    )
    invoiced_date = fields.Date(
        string='Invoiced Date',
        copy=False,
    )
    is_billable = fields.Boolean(
        string='Billable',
        default=True,
        help='Uncheck to exclude this line from billing calculations.',
    )

    # ------------------------------------------------------------------
    # ORM overrides
    # ------------------------------------------------------------------

    @api.model_create_multi
    def create(self, vals_list):
        records = super().create(vals_list)
        records._maybe_push_to_convergence()
        return records

    def write(self, vals):
        result = super().write(vals)
        # Only re-push if relevant fields changed and convergence_id not yet set
        convergence_fields = {
            'unit_amount', 'date', 'employee_id', 'task_id',
            'project_id', 'name', 'time_in', 'time_out',
        }
        if convergence_fields.intersection(vals.keys()):
            self.filtered(lambda r: not r.convergence_time_id)._maybe_push_to_convergence()
        return result

    # ------------------------------------------------------------------
    # Convergence integration
    # ------------------------------------------------------------------

    def _maybe_push_to_convergence(self):
        """Push lines to Convergence if URL configured and no id yet."""
        ICP = self.env['ir.config_parameter'].sudo()
        convergence_url = ICP.get_param('jb_timesheet.convergence_api_url', default='')
        if not convergence_url:
            return
        for line in self:
            if not line.convergence_time_id:
                line._push_to_convergence()

    def _push_to_convergence(self):
        """POST this timesheet line to the Convergence API."""
        self.ensure_one()
        ICP = self.env['ir.config_parameter'].sudo()
        convergence_url = ICP.get_param('jb_timesheet.convergence_api_url', default='')
        if not convergence_url:
            _logger.debug('jb_timesheet: Convergence URL not configured, skipping push.')
            return

        auth_token = ICP.get_param('jb_timesheet.convergence_api_token', default='')
        headers = {'Content-Type': 'application/json'}
        if auth_token:
            headers['Authorization'] = f'Bearer {auth_token}'

        payload = {
            'date': str(self.date),
            'duration': self.unit_amount,
            'description': self.name or '',
            'employee_eit_id': self.employee_id.eit_user_id or '',
            'project_eit_id': self.project_id.eit_project_id or '' if self.project_id else '',
            'task_name': self.task_id.name or '' if self.task_id else '',
            'time_in': self.time_in,
            'time_out': self.time_out,
        }

        try:
            response = requests.post(
                convergence_url,
                data=json.dumps(payload),
                headers=headers,
                timeout=15,
            )
            response.raise_for_status()
            data = response.json()
            convergence_id = data.get('id') or data.get('convergence_id') or data.get('time_id')
            if convergence_id:
                self.sudo().write({'convergence_time_id': str(convergence_id)})
                _logger.info(
                    'jb_timesheet: Pushed line %s to Convergence, id=%s',
                    self.id, convergence_id,
                )
            else:
                _logger.warning(
                    'jb_timesheet: Convergence response had no id field: %s',
                    data,
                )
        except RequestException as exc:
            _logger.error(
                'jb_timesheet: Convergence push failed for line %s: %s',
                self.id, exc,
            )
