# -*- coding: utf-8 -*-
from odoo import api, fields, models


class AccountAnalyticLine(models.Model):
    _inherit = 'account.analytic.line'

    partner_id = fields.Many2one(
        comodel_name='res.partner',
        string='Client',
        related='project_id.partner_id',
        store=True,
        readonly=True,
    )
    project_item_display = fields.Char(
        string='Project / Item',
        compute='_compute_project_item_display',
    )
    duration_display = fields.Char(
        string='Duration',
        compute='_compute_duration_display',
    )
    hourly_rate = fields.Float(
        string='Rate',
        help='Hourly billing rate used to calculate amount.',
    )
    amount = fields.Monetary(
        string='Amount',
        compute='_compute_amount',
        store=True,
        currency_field='currency_id',
    )
    currency_id = fields.Many2one(
        comodel_name='res.currency',
        related='company_id.currency_id',
        readonly=True,
    )
    billable_flag = fields.Char(
        string='Bill',
        compute='_compute_billable_flag',
    )
    is_internal = fields.Boolean(
        string='Internal',
        compute='_compute_is_internal',
        store=True,
    )

    @api.depends('project_id', 'task_id')
    def _compute_project_item_display(self):
        for line in self:
            project = line.project_id.name or ''
            task = line.task_id.name or ''
            if project and task:
                line.project_item_display = f'{project}: {task}'
            else:
                line.project_item_display = project or task or ''

    @api.depends('time_in', 'time_out')
    def _compute_duration_display(self):
        for line in self:
            if line.time_in or line.time_out:
                line.duration_display = '%s - %s' % (
                    line._format_clock(line.time_in),
                    line._format_clock(line.time_out),
                )
            else:
                line.duration_display = ''

    @api.depends('unit_amount', 'hourly_rate', 'employee_id.hourly_rate', 'is_billable')
    def _compute_amount(self):
        for line in self:
            rate = line.hourly_rate or line.employee_id.hourly_rate or 0.0
            line.amount = line.unit_amount * rate if line.is_billable else 0.0

    @api.depends('is_billable')
    def _compute_billable_flag(self):
        for line in self:
            line.billable_flag = 'Y' if line.is_billable else 'N'

    @api.depends('partner_id', 'partner_id.name')
    def _compute_is_internal(self):
        for line in self:
            name = (line.partner_id.name or '').lower()
            line.is_internal = name in ('internal', '') or not line.partner_id

    @staticmethod
    def _format_clock(value):
        """Convert 24h decimal (9.5) to HH:MM."""
        if not value:
            return '--:--'
        hours = int(value)
        minutes = int(round((value - hours) * 60))
        if minutes == 60:
            hours += 1
            minutes = 0
        return '%02d:%02d' % (hours, minutes)

    @staticmethod
    def _clock_to_float(clock_str):
        if not clock_str or ':' not in clock_str:
            return 0.0
        parts = clock_str.split(':')
        return int(parts[0]) + (int(parts[1]) / 60.0)

    @api.onchange('time_in', 'time_out')
    def _onchange_time_range(self):
        if self.time_in and self.time_out and self.time_out > self.time_in:
            self.unit_amount = round(self.time_out - self.time_in, 2)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if not vals.get('hourly_rate') and vals.get('employee_id'):
                employee = self.env['hr.employee'].browse(vals['employee_id'])
                vals['hourly_rate'] = employee.hourly_rate
        return super().create(vals_list)
