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


class NacefTenantBeacon(models.Model):
    """Fleet-health beacon pushed by a tenant database.

    Carries metadata only (S-MDF status, connectivity, offline budget, cert
    expiry, integrity-check result) — never fiscal content — so the operator
    gets fleet visibility without reading into tenant fiscal tables.
    """
    _name = "nacef.tenant.beacon"
    _description = "NACEF Fleet Health Beacon"
    _order = "received_at desc"

    tenant_id = fields.Many2one(
        "nacef.tenant", required=True, ondelete="cascade", index=True)
    imdf = fields.Char(required=True, index=True)
    smdf_status = fields.Char()
    connection_state = fields.Char()
    offline_tickets = fields.Integer()
    cert_days_to_expiry = fields.Integer()
    integrity_ok = fields.Boolean(default=True)
    received_at = fields.Datetime(default=fields.Datetime.now, readonly=True)

    @api.model
    def ingest(self, payload):
        """Ingest one beacon. Resolves the tenant by matricule or db_name, stores
        the beacon and refreshes the IMDF's last-reported status. Returns the
        beacon record."""
        tenant = self.env["nacef.tenant"]
        matricule = payload.get("matricule")
        db_name = payload.get("db_name")
        imdf_code = payload.get("imdf")
        if matricule:
            tenant = tenant.search(
                [("matricule_fiscal", "=", matricule)], limit=1)
        if not tenant and db_name:
            tenant = tenant.search([("db_name", "=", db_name)], limit=1)
        if not tenant:
            raise UserError("Beacon references an unknown tenant.")
        beacon = self.create({
            "tenant_id": tenant.id,
            "imdf": imdf_code,
            "smdf_status": payload.get("status"),
            "connection_state": payload.get("state"),
            "offline_tickets": payload.get("offline_tickets", 0),
            "cert_days_to_expiry": payload.get("cert_days_to_expiry", 0),
            "integrity_ok": payload.get("integrity_ok", True),
        })
        imdf = self.env["nacef.tenant.imdf"].search(
            [("tenant_id", "=", tenant.id), ("imdf", "=", imdf_code)], limit=1)
        if imdf:
            imdf.write({
                "last_status": payload.get("status"),
                "last_connection": payload.get("state"),
                "last_offline_tickets": payload.get("offline_tickets", 0),
                "last_beacon_date": fields.Datetime.now(),
            })
        return beacon
