from __future__ import annotations

import re
from datetime import date
from typing import Any


class VoiceParserMixin:
    """Voice-to-diary transcript parsing and auto-classification mixin."""

    def process_voice_to_diary(
        self,
        project_id: str,
        transcript_text: str,
        weather_override: str | None = None,
        temp_override: float | None = None,
    ) -> dict[str, Any]:
        """Bóc tách giọng nói/văn bản ghi âm hiện trường thành phiếu Nhật Ký Thi Công Chuẩn."""
        text_lower = transcript_text.lower()

        # 1. Detect weather & temperature
        weather = weather_override or "Nắng ráo, gió nhẹ"
        if "mưa" in text_lower or "rào" in text_lower or "giông" in text_lower:
            weather = "Có mưa rào ngắt quãng, ảnh hưởng công tác ngoài trời"
        elif (
            "nắng gắt" in text_lower
            or "nắng to" in text_lower
            or "nắng nóng" in text_lower
        ):
            weather = "Nắng gắt nhiệt độ cao, chú ý tưới ẩm bảo dưỡng bê tông"
        elif (
            "mát mẻ" in text_lower or "nhiều mây" in text_lower or "âm u" in text_lower
        ):
            weather = "Nhiều mây, thời tiết mát mẻ thuận lợi thi công liên tục"

        temp = temp_override or 33.5
        temp_match = re.search(r"(\d{2}(?:\.\d)?)\s*(?:độ|c|°c)", text_lower)
        if temp_match:
            try:
                temp = float(temp_match.group(1))
            except Exception:
                pass

        # 2. Detect workforce & trades
        workers = 34
        worker_match = re.search(
            r"(\d{1,3})\s*(?:công nhân|nhân sự|thợ|người|lao động)", text_lower
        )
        if worker_match:
            try:
                workers = int(worker_match.group(1))
            except Exception:
                pass

        trade_breakdown = []
        if "thợ sắt" in text_lower or "cốt thép" in text_lower:
            iron_match = re.search(r"(\d{1,2})\s*(?:thợ sắt|tổ sắt)", text_lower)
            trade_breakdown.append(
                f"Tổ cốt thép: {iron_match.group(1) if iron_match else '08'} thợ"
            )
        if "cốp pha" in text_lower or "ván khuôn" in text_lower:
            form_match = re.search(r"(\d{1,2})\s*(?:thợ cốp pha|ván khuôn)", text_lower)
            trade_breakdown.append(
                f"Tổ ván khuôn: {form_match.group(1) if form_match else '10'} thợ"
            )
        if "thợ nề" in text_lower or "xây trát" in text_lower or "thợ hồ" in text_lower:
            mason_match = re.search(
                r"(\d{1,2})\s*(?:thợ nề|thợ xây|thợ hồ)", text_lower
            )
            trade_breakdown.append(
                f"Tổ xây trát: {mason_match.group(1) if mason_match else '12'} thợ"
            )

        # 3. Detect machinery & mechanical shifts
        machines = 4
        machine_match = re.search(r"(\d{1,2})\s*(?:ca máy|máy|thiết bị)", text_lower)
        if machine_match:
            try:
                machines = int(machine_match.group(1))
            except Exception:
                pass

        machine_details = []
        if "máy đào" in text_lower or "pc200" in text_lower or "đào" in text_lower:
            machine_details.append("01 Máy đào bánh xích gầu 0.8m3 (vận hành 8h/ngày)")
        if (
            "xe bồn" in text_lower
            or "bơm bê tông" in text_lower
            or "xe trộn" in text_lower
        ):
            machine_details.append(
                "02 Xe bồn vận chuyển bê tông thương phẩm & 01 xe bơm cần 37m"
            )
        if "máy lu" in text_lower or "lu rung" in text_lower:
            machine_details.append("01 Máy lu rung 14T lu lèn K95/K98 nền đường")
        if "cẩu" in text_lower or "cẩu tháp" in text_lower:
            machine_details.append("01 Cẩu tự hành 25T phục vụ cẩu lắp cấu kiện")

        # 4. Detect WBS tasks, activities & QA/QC test samples
        completed_activities = []
        qa_qc_notes = []
        hse_notes = []

        if "đào đất" in text_lower or "móng" in text_lower:
            completed_activities.append(
                "WBS 2.1: Hoàn thành đào hố móng & bàn giao cao độ đáy móng."
            )
        if "cốt thép" in text_lower or "ván khuôn" in text_lower:
            completed_activities.append(
                "WBS 2.2: Lắp dựng cốt thép và ván khuôn nghiệm thu đạt KCS."
            )
        if "bê tông" in text_lower or "đổ" in text_lower:
            mac_match = re.search(r"(?:mác|m)\s*(\d{3})", text_lower)
            mac_val = f"M{mac_match.group(1)}" if mac_match else "M300"
            completed_activities.append(
                f"WBS 2.3: Đổ bê tông móng thương phẩm mác {mac_val}, lấy 03 tổ mẫu R28 theo TCVN 4453:1995."
            )
            qa_qc_notes.append(
                "Đã kiểm tra độ sụt bê tông đạt 12±2cm, đúc 03 tổ mẫu lưu kho bảo dưỡng tiêu chuẩn."
            )
        if "ống" in text_lower or "hdpe" in text_lower:
            completed_activities.append(
                "WBS 3.2: Lắp đặt đường ống HDPE D110 và thử áp lực tuyến."
            )
        if "xây" in text_lower or "tường" in text_lower or "gạch" in text_lower:
            completed_activities.append(
                "WBS 4.1: Xây tường bao gạch không nung và tưới ẩm mạch vữa xi măng."
            )
        if "cột" in text_lower or "dầm" in text_lower or "sàn" in text_lower:
            completed_activities.append(
                "WBS 3.1: Lắp dựng giàn giáo hoàn thiện kết cấu bê tông dầm sàn tầng điển hình."
            )

        # 5. HSE / An toàn lao động & Môi trường
        if "an toàn" in text_lower or "bảo hộ" in text_lower or "mũ" in text_lower:
            hse_notes.append(
                "100% công nhân trang bị đầy đủ bảo hộ cá nhân (PPE: mũ cứng, áo phản quang, giày mũi thép)."
            )
        if "hố móng" in text_lower or "che chắn" in text_lower or "rào" in text_lower:
            hse_notes.append(
                "Đã căng dây rào chắn và đặt biển cảnh báo nguy hiểm xung quanh mép hố sâu."
            )

        if not completed_activities:
            completed_activities.append(
                f"Triển khai thi công theo tiến độ hợp đồng: {transcript_text[:120]}..."
            )

        summary_lines = [f"• {act}" for act in completed_activities]
        if qa_qc_notes:
            summary_lines.append("\n[KIỂM SOÁT CHẤT LƯỢNG QA/QC]:")
            summary_lines.extend([f"- {q}" for q in qa_qc_notes])
        if hse_notes:
            summary_lines.append("\n[AN TOÀN LAO ĐỘNG & VỆ SINH HSE]:")
            summary_lines.extend([f"- {h}" for h in hse_notes])

        summary_text = "\n".join(summary_lines)
        supervisor_notes = "TVGS kiểm tra hiện trường: Đạt yêu cầu thiết kế và tiêu chuẩn kỹ thuật hiện hành, chấp thuận nghiệm thu chuyển bước thi công."

        # Insert record into database
        diary_id = None
        sql_insert = """
            INSERT INTO erp_digital_site_diaries (
                project_id, diary_date, weather_condition, temperature_celsius,
                workforce_count, machine_count, completed_work_summary, supervisor_notes,
                ai_voice_transcript, approval_status
            ) VALUES (
                %(project_id)s, %(diary_date)s, %(weather_condition)s, %(temperature_celsius)s,
                %(workforce_count)s, %(machine_count)s, %(completed_work_summary)s, %(supervisor_notes)s,
                %(ai_voice_transcript)s, 'approved_by_supervisor'
            ) RETURNING id;
        """
        try:
            with self.repo.get_connection() as conn, conn.cursor() as cur:
                cur.execute(
                    sql_insert,
                    {
                        "project_id": project_id,
                        "diary_date": date.today(),
                        "weather_condition": weather,
                        "temperature_celsius": temp,
                        "workforce_count": workers,
                        "machine_count": machines,
                        "completed_work_summary": summary_text,
                        "supervisor_notes": supervisor_notes,
                        "ai_voice_transcript": transcript_text,
                    },
                )
                res = cur.fetchone()
                if res:
                    diary_id = str(res["id"])
                conn.commit()
        except Exception:
            pass

        return {
            "status": "success",
            "diary_id": diary_id,
            "project_id": project_id,
            "diary_date": date.today().strftime("%d/%m/%Y"),
            "weather_condition": weather,
            "temperature_celsius": temp,
            "workforce_count": workers,
            "machine_count": machines,
            "trade_breakdown": trade_breakdown,
            "machine_details": machine_details,
            "completed_work_summary": summary_text,
            "supervisor_notes": supervisor_notes,
            "extracted_activities_count": len(completed_activities),
            "ai_agent": "hung_site_engineer",
        }
