# -*- coding: utf-8 -*-
"""LVT4U — Legal Documents Library.

Categorized viewer for Vietnamese forestry legal documents,
TCVN standards, and regulatory circulars. Supports both local
files (docs/ folder) and online reference links.

When a document file exists locally, it opens with the system's
default application. Otherwise, it opens the online reference URL.

Author: Lộc Vũ Trung (LVT) / Slow Forest
License: GPL-3.0
"""

import os

from qgis.PyQt.QtCore import Qt, QUrl
from ..shared.qt_compat import QtCompat
from qgis.PyQt.QtGui import QDesktopServices, QFont
from qgis.PyQt.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QTabWidget,
    QWidget, QScrollArea, QFrame,
)

from ..shared.i18n import tr, current_language

_DOCS_DIR = os.path.dirname(__file__)
_LOCAL_DOCS = os.path.join(_DOCS_DIR, "docs")

# ── Document catalog ──────────────────────────────────────────────────
# Each category: {icon, vi, en, docs}
# Each doc: (filename, vi_title, en_title, google_drive_url)
# filename is kept for backward compat; url points to Google Drive.
_CATALOG = [
    {
        "icon": "📜",
        "vi": "Thông tư",
        "en": "Circulars",
        "docs": [
            ("TT84_2025_BNNMT.pdf",
             "TT 84/2025/TT-BNNMT — Quy định chi tiết Luật Lâm nghiệp & sửa đổi TT lĩnh vực lâm nghiệp ⭐ MỚI",
             "Circular 84/2025 — Detailed provisions of Forestry Law & amendments ⭐ NEW",
             "https://lvtfield.lvtcenter.it.com/downloads/docs/Thong_tu_84_2025_TT-BNNMT_PDF.pdf"),
            ("TT16_2025_BNNMT.pdf",
             "TT 16/2025/TT-BNNMT — Phân quyền, phân cấp trong lĩnh vực lâm nghiệp và kiểm lâm ⭐ MỚI",
             "Circular 16/2025 — Authority delegation in forestry & ranger management ⭐ NEW",
             "https://lvtfield.lvtcenter.it.com/downloads/docs/Thong_tu_16_2025_TT-BNNMT_PDF.pdf"),
            ("TT11_2024_BNNPTNT.pdf",
             "TT 11/2024/TT-BNNPTNT — Định mức KTKT kiểm kê rừng, theo dõi diễn biến rừng ⭐ MỚI",
             "Circular 11/2024 — Technical norms for forest inventory & monitoring ⭐ NEW",
             "https://lvtfield.lvtcenter.it.com/downloads/docs/Thong_tu_11_2024_TT-BNNPTNT_PDF.pdf"),
            ("TT16_2023_BNN.pdf",
             "TT 16/2023/TT-BNNPTNT — Sửa đổi TT33 về điều tra, kiểm kê rừng",
             "Circular 16/2023 — Amendment to Circular 33 on forest inventory",
             "https://drive.google.com/file/d/17AarQmWVFQMKWAwwFj5SQsvzI67FGz3c/view"),
            ("TT16_PhuLuc_45_46.doc",
             "TT 16 — Phụ lục 45 + 46",
             "Circular 16 — Appendix 45 + 46",
             "https://drive.google.com/file/d/1DxPt8qimNpGx_Z-bARPbohWXKTggqBLT/view"),
            ("TT16_PhuLuc_47_48.doc",
             "TT 16 — Phụ lục 47 + 48",
             "Circular 16 — Appendix 47 + 48",
             "https://drive.google.com/file/d/1mFNVre6drgKAVwqKsqOyN_h3Z_JN9w6X/view"),
            ("TT25_2009_ThongKe_KiemKeRung.doc",
             "TT 25/2009 — Thống kê, kiểm kê rừng & lập hồ sơ quản lý rừng (hết hiệu lực)",
             "Circular 25/2009 — Forest inventory & management dossier (expired)",
             "https://drive.google.com/file/d/1lGC6RU50fmjjxNuNbuCUS7lBiKxLcGGM/view"),
            ("TT33_2018_DieuTraRung.doc",
             "TT 33/2018 — Điều tra, kiểm kê và theo dõi diễn biến rừng",
             "Circular 33/2018 — Forest investigation, inventory & monitoring",
             "https://drive.google.com/file/d/1jGTOemJMBNs5TJh_8X91DCaiB8ivuf5N/view"),
            ("TT34_2009_PhanLoaiRung_VI.doc",
             "TT 34/2009 — Tiêu chí xác định và phân loại rừng (VN) (hết hiệu lực)",
             "Circular 34/2009 — Forest classification criteria (Vietnamese, expired)",
             "https://drive.google.com/file/d/1IxLH48PUsdzcBmu-rDyrBJBPFuafav_I/view"),
            ("TT34_2009_PhanLoaiRung_EN.doc",
             "TT 34/2009 — Tiêu chí xác định và phân loại rừng (EN) (hết hiệu lực)",
             "Circular 34/2009 — Forest classification criteria (English, expired)",
             "https://drive.google.com/file/d/18Yusu6g_I2caqBJV2oEWiHhTTr9x-TXp/view"),
        ],
    },
    {
        "icon": "🔬",
        "vi": "Điều tra rừng",
        "en": "Forest Investigation",
        "docs": [
            ("TT05_2024_DinhMuc_KTKT_DieuTraRung.pdf",
             "TT 05/2024/TT-BNNPTNT — Định mức KTKT Điều tra rừng",
             "Circular 05/2024 — Technical norms for forest investigation",
             "https://drive.google.com/file/d/1PRvaFN2-T4c4yCY3UYYDd19DOpE9PAP7/view"),
            ("TT05_2024_PhuLuc_09_5.pdf",
             "TT 05/2024 — Phụ lục 09.5 (ĐM KTKT chi tiết)",
             "Circular 05/2024 — Appendix 09.5 (detailed norms)",
             "https://drive.google.com/file/d/1DxCEEpi_ltM7FZHWe36z-Efe3v5yUORD/view"),
            ("QD243_SoTay_KTNT_KKR.pdf",
             "QĐ 243 — Sổ tay KTNT Kiểm kê rừng",
             "Decision 243 — Field manual for forest inventory",
             "https://drive.google.com/file/d/1DdIIdcKebZf6ShEOAApMQPjVmTWsGB_X/view"),
            ("HDKT_DieuTraRung.pdf",
             "HDKT ĐTR — Hướng dẫn kỹ thuật điều tra rừng",
             "Technical guide for forest investigation",
             "https://drive.google.com/file/d/1GzXS58VpoV30I8SjSBZmgp5FsncKV5TG/view"),
        ],
    },
    {
        "icon": "📐",
        "vi": "Bản đồ & Hệ tọa độ",
        "en": "Maps & Coordinate Systems",
        "docs": [
            ("TT24_2025_BNNMT.pdf",
             "TT 24/2025/TT-BNNMT — Bản đồ hành chính, kinh tuyến trục VN-2000 theo 34 tỉnh mới 2025 ⭐ MỚI",
             "Circular 24/2025 — Administrative maps, VN-2000 central meridians for 34 post-merger provinces ⭐ NEW",
             "https://lvtfield.lvtcenter.it.com/downloads/docs/Thong_tu_24_2025_TT-BNNMT_PDF.pdf"),
            ("TCVN_11565_2016_BanDo_HienTrangRung_LVT.pdf",
             "TCVN 11565:2016 — Bản đồ hiện trạng rừng",
             "TCVN 11565:2016 — Forest status map standard",
             "https://drive.google.com/file/d/1mN83Lvm46XvWTDu8F0UaWRPmu4NQErGn/view"),
            ("TCVN_11566_2016_BanDo_QuyHoachLamNghiep_LVT.pdf",
             "TCVN 11566:2016 — Bản đồ quy hoạch lâm nghiệp",
             "TCVN 11566:2016 — Forestry planning map standard",
             "https://drive.google.com/file/d/17m0-nksh_5VYmm7xkndiAxGlF2La6Vqw/view"),
            ("QD689_2013_HD_XayDung_BienTap_BanDo_DTKK_Rung.docx",
             "QĐ 689/QĐ-TCLN-KL (2013) — Hướng dẫn xây dựng, biên tập bản đồ điều tra, kiểm kê rừng",
             "Decision 689/TCLN-KL (2013) — Guide for building & editing forest inventory maps",
             "https://docs.google.com/document/d/1kgFtsSbKXZ3tBjDR-AtMCEIn7WAl58WI/view"),
        ],
    },
    {
        "icon": "🌲",
        "vi": "Rừng trồng",
        "en": "Plantation Standards",
        "docs": [
            ("TCVN_11567_1_2016_RungTrong_Phan1.pdf",
             "TCVN 11567-1:2016 — Rừng trồng gỗ lớn — Phần 1: Keo lai",
             "TCVN 11567-1:2016 — Plantation forest — Part 1: Acacia hybrid",
             "https://drive.google.com/file/d/1L_knsMwrubMzhFIIgHEevrenA0LtLW2B/view"),
            ("TCVN_11567_2_2016_RungTrong_Phan2.pdf",
             "TCVN 11567-2:2016 — Rừng trồng gỗ lớn — Phần 2: Keo tai tượng",
             "TCVN 11567-2:2016 — Plantation forest — Part 2: A. mangium",
             "https://drive.google.com/file/d/1XvWB7wROPmeBr5ci6-9d27dcj765kCPL/view"),
            ("TCVN_12509_2018_RungTrong_SauKienThiet.doc",
             "TCVN 12509:2018 — Rừng trồng sau thời gian kiến thiết cơ bản",
             "TCVN 12509:2018 — Plantation after basic construction",
             "https://drive.google.com/file/d/1fNSYu5_c3vRIF3v142MyLd_TZghUbfm_/view"),
        ],
    },
    {
        "icon": "🔥",
        "vi": "Phòng cháy rừng",
        "en": "Forest Fire Prevention",
        "docs": [
            ("TCVN_14274_2025_PhongChayRung.pdf",
             "TCVN 14274:2025 — Phòng cháy chữa cháy rừng — Yêu cầu chung",
             "TCVN 14274:2025 — Forest fire prevention — General requirements",
             "https://drive.google.com/file/d/12UOG-8cBmCFhEEXhwnfDAAzYjtwY-6aL/view"),
            ("TCVN_2025_CapDuBao_ChayRung.pdf",
             "TCVN 2025 — Cấp dự báo cháy rừng",
             "TCVN 2025 — Forest fire forecast classification",
             "https://drive.google.com/file/d/1mL6QwKBUrc2t6HFDtgdjbpICuIdqPJuv/view"),
        ],
    },
    {
        "icon": "📋",
        "vi": "Quyết định & Tiêu chuẩn khác",
        "en": "Decisions & Other Standards",
        "docs": [
            ("QD_04_2004_QuyCheKhaiThacGo.doc",
             "QĐ 04/2004/QĐ-BNN-LN — Quy chế khai thác gỗ và lâm sản",
             "Decision 04/2004 — Timber & forest product exploitation regulations",
             "https://drive.google.com/file/d/1FB8bTKyiDYFKnBIidqf8TJHk6GQ8JD_K/view"),
            ("QD_4215_BKHCN_CongBo_TCVN.doc",
             "QĐ 4215/QĐ-BKHCN — Công bố TCVN lâm nghiệp (30/12/2016)",
             "Decision 4215/MOST — Publication of forestry TCVN standards",
             "https://drive.google.com/file/d/1F0WbIsofSbnj0tkzFrbF09KbKJpRifXg/view"),
            ("TCN_74_2006_PhanLoaiGoTron.doc",
             "04 TCN 74:2006 — Phân loại gỗ tròn",
             "04 TCN 74:2006 — Round timber classification",
             "https://drive.google.com/file/d/19scRdeJqA5Gj_jIRnhTDrZ8MOP2Ewt-L/view"),
            ("TCN_126_2006_TrongCayGoLon.doc",
             "04 TCN 126:2006 — Hướng dẫn kỹ thuật trồng cây gỗ lớn",
             "04 TCN 126:2006 — Large timber planting technical guide",
             "https://drive.google.com/file/d/1C5R7uCr-y3ZRhb0SPvdt7YvPr438IjMB/view"),
            ("TCN_132_2006_SinhTruong_KeoLai.doc",
             "04 TCN 132:2006 — Biểu sinh trưởng rừng keo lai",
             "04 TCN 132:2006 — Acacia hybrid growth tables",
             "https://drive.google.com/file/d/1cJcpZ33jNKFM2ogBNYKoz-gGqdtHlELg/view"),
            ("TCVN_13353_2021_LamNghiep.doc",
             "TCVN 13353:2021 — Mẫu khóa ảnh vệ tinh phục vụ bản đồ hiện trạng rừng",
             "TCVN 13353:2021 — Satellite image interpretation keys for forest mapping",
             "https://drive.google.com/file/d/1NxYdngvuWrFAN_1bYyO4J2DCiUEQhi2Q/view"),
            ("DanhMuc_TieuChuan_LamNghiep.pdf",
             "Danh mục tiêu chuẩn Việt Nam về lâm nghiệp",
             "Catalog of Vietnamese forestry standards",
             "https://drive.google.com/file/d/1y8H7RrGaeTi7gNETWlMOmRhs1LzGjIjv/view"),
        ],
    },
    {
        "icon": "⚖️",
        "vi": "Luật",
        "en": "Laws",
        "docs": [
            ("Luat_31_2024_QH15.pdf",
             "Luật 31/2024/QH15 — Sửa đổi, bổ sung một số điều của Luật Lâm nghiệp ⭐ MỚI",
             "Law 31/2024/QH15 — Amendments to Forestry Law ⭐ NEW",
             "https://lvtfield.lvtcenter.it.com/downloads/docs/Luat_31_2024_QH15_PDF.pdf"),
            ("Luat_146_2025_QH15.pdf",
             "Luật 146/2025/QH15 — Luật Đất đai / Tài nguyên Môi trường ⭐ MỚI",
             "Law 146/2025/QH15 — Land / Natural Resources & Environment Law ⭐ NEW",
             "https://lvtfield.lvtcenter.it.com/downloads/docs/Luat_146_2025_QH15_PDF.pdf"),
        ],
    },
]


class LegalDocsDialog(QDialog):
    """Categorized Legal Documents Library dialog.

    Supports dual-mode access: local file (docs/ folder) or online
    reference URL. When the local file is present, it opens with the
    system's default app. Otherwise, it opens the online link in a
    browser.
    """

    def __init__(self, iface, parent=None):
        super().__init__(parent or iface.mainWindow())
        self.iface = iface
        self.setWindowTitle("LVT4U — " + tr("Legal Documents"))
        self.setWindowFlags(
            self.windowFlags() & ~QtCompat.WindowContextHelpButtonHint)
        self.setMinimumWidth(680)
        self.setMinimumHeight(520)
        self._build_ui()

    def _build_ui(self):
        root = QVBoxLayout(self)
        root.setContentsMargins(8, 8, 8, 8)

        # Header
        hdr = QLabel("📚  " + tr("Legal Documents"))
        hdr.setFont(QFont("Segoe UI", 14, QFont.Weight.Bold))
        hdr.setStyleSheet("color:#5d4037; padding:4px;")
        root.addWidget(hdr)

        lang = current_language()

        # Count
        total = sum(len(cat["docs"]) for cat in _CATALOG)
        subtitle = (
            f"Thư viện {total} văn bản pháp lý ngành lâm nghiệp Việt Nam"
            if lang == "vi" else
            f"Library of {total} Vietnamese forestry legal documents"
        )
        sub = QLabel(subtitle)
        sub.setStyleSheet(
            "color:#888; font-size:11px; padding:0 4px 4px 4px;")
        root.addWidget(sub)

        # Legend
        legend_text = (
            "☁️ Google Drive — cần Internet  |"
            " 📂 Tài liệu cục bộ (mở ngay)"
            if lang == "vi" else
            "☁️ Google Drive — requires Internet  |"
            " 📂 Local document (opens instantly)"
        )
        legend = QLabel(legend_text)
        legend.setStyleSheet(
            "color:#999; font-size:10px; padding:0 4px 2px 4px;"
            "font-style:italic;")
        root.addWidget(legend)

        # Tabs
        tabs = QTabWidget()
        root.addWidget(tabs, 1)

        for cat in _CATALOG:
            tab_title = f'{cat["icon"]} {cat[lang]}'
            tab = QWidget()
            tabs.addTab(tab, tab_title)
            self._build_doc_list(tab, cat["docs"], lang)

        # Bottom buttons
        bottom = QHBoxLayout()
        btn_help = QPushButton("❓ " + tr("Help"))
        btn_help.setMinimumHeight(36)
        btn_help.setStyleSheet(
            "QPushButton{background:#ff8f00;color:white;border-radius:5px;"
            "padding:6px 14px;font-weight:bold;}"
            "QPushButton:hover{background:#ffa000;}"
        )
        btn_help.clicked.connect(self._show_help)
        bottom.addWidget(btn_help)
        bottom.addStretch()
        btn_close = QPushButton(tr("Close"))
        btn_close.setMinimumHeight(36)
        btn_close.setStyleSheet(
            "QPushButton{background:#757575;color:white;border-radius:5px;"
            "padding:6px 20px;}"
            "QPushButton:hover{background:#616161;}"
        )
        btn_close.clicked.connect(self.close)
        bottom.addWidget(btn_close)
        root.addLayout(bottom)

    def _build_doc_list(self, parent, docs, lang):
        ly = QVBoxLayout(parent)
        ly.setSpacing(0)
        ly.setContentsMargins(4, 4, 4, 4)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(QFrame.Shape.NoFrame)

        container = QWidget()
        inner = QVBoxLayout(container)
        inner.setSpacing(6)

        for filename, vi_title, en_title, drive_url in docs:
            title = vi_title if lang == "vi" else en_title
            ext = os.path.splitext(filename)[1].upper().replace(".", "")

            # Check for local file first
            local_path = os.path.join(_LOCAL_DOCS, filename)
            if os.path.exists(local_path):
                src_icon = "📂"  # local folder icon
                btn = QPushButton(f"{src_icon}  {title}")
                btn.setFont(QFont("Segoe UI", 10))
                btn.setMinimumHeight(38)
                btn.setCursor(QtCompat.PointingHandCursor)
                btn.setStyleSheet(
                    "QPushButton{text-align:left;padding:6px 12px;"
                    "background:#E8F5E9;border:1px solid #A5D6A7;"
                    "border-radius:4px;}"
                    "QPushButton:hover{background:#C8E6C9;"
                    "border-color:#66BB6A;}"
                )
                local_url = QUrl.fromLocalFile(local_path)
                btn.setToolTip(f"📂 Cục bộ: {filename}")
                btn.clicked.connect(
                    lambda checked, u=local_url: QDesktopServices.openUrl(u)
                )
            elif drive_url:
                src_icon = "📄" if ext == "PDF" else "📝"
                btn = QPushButton(f"{src_icon}  {title}")
                btn.setFont(QFont("Segoe UI", 10))
                btn.setMinimumHeight(38)
                btn.setCursor(QtCompat.PointingHandCursor)
                btn.setStyleSheet(
                    "QPushButton{text-align:left;padding:6px 12px;"
                    "background:#E3F2FD;border:1px solid #90CAF9;"
                    "border-radius:4px;}"
                    "QPushButton:hover{background:#BBDEFB;"
                    "border-color:#42A5F5;}"
                )
                btn.setToolTip(f"☁️ Google Drive: {filename}")
                btn.clicked.connect(
                    lambda checked, u=drive_url: self._open_url(u)
                )
            else:
                src_icon = "📄" if ext == "PDF" else "📝"
                btn = QPushButton(f"{src_icon}  {title}")
                btn.setFont(QFont("Segoe UI", 10))
                btn.setMinimumHeight(38)
                btn.setStyleSheet(
                    "QPushButton{text-align:left;padding:6px 12px;"
                    "background:#FFEBEE;border:1px solid #EF9A9A;"
                    "border-radius:4px;color:#999;}"
                )
                btn.setToolTip(
                    "Chưa có link" if lang == "vi"
                    else "Link not available"
                )
                btn.setEnabled(False)

            inner.addWidget(btn)

        inner.addStretch()
        scroll.setWidget(container)
        ly.addWidget(scroll)

    @staticmethod
    def _open_url(url):
        """Open a Google Drive URL in the default browser."""
        QDesktopServices.openUrl(QUrl(url))

    def _show_help(self):
        """Open help dialog for Legal Docs module."""
        from ..shared.help_dialog import HelpDialog
        dlg = HelpDialog("legal_docs", parent=self)
        dlg.exec()
