# -*- 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 qgis.PyQt.QtGui import QDesktopServices, QFont
from qgis.PyQt.QtWidgets import (
    QDialog, QVBoxLayout, QLabel, QPushButton, QTabWidget,
    QWidget, QScrollArea, QFrame,
)

from ..shared.i18n import tr, current_language

_DOCS_DIR = os.path.dirname(__file__)

# ── Document catalog ──────────────────────────────────────────────────
# Each category: {icon, vi, en, docs}
# Each doc: (filename, vi_title, en_title, online_url)
_CATALOG = [
    {
        "icon": "📜",
        "vi": "Thông tư",
        "en": "Circulars",
        "docs": [
            ("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://congbao.chinhphu.vn/noi-dung-van-ban-so-16-2023-tt-bnnptnt-58561"),
            ("TT16_PhuLuc_45_46.doc",
             "TT 16 — Phụ lục 45 + 46",
             "Circular 16 — Appendix 45 + 46",
             "https://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Thong-tu-16-2023-TT-BNNPTNT-sua-doi-Thong-tu-33-2018-TT-BNNPTNT-kiem-ke-rung-590492.aspx"),
            ("TT16_PhuLuc_47_48.doc",
             "TT 16 — Phụ lục 47 + 48",
             "Circular 16 — Appendix 47 + 48",
             "https://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Thong-tu-16-2023-TT-BNNPTNT-sua-doi-Thong-tu-33-2018-TT-BNNPTNT-kiem-ke-rung-590492.aspx"),
            ("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://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Thong-tu-25-2009-TT-BNN-huong-dan-thong-ke-kiem-ke-rung-va-lap-ho-so-quan-ly-rung-88714.aspx"),
            ("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://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Thong-tu-33-2018-TT-BNNPTNT-kiem-ke-theo-doi-dien-bien-rung-399587.aspx"),
            ("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://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Thong-tu-34-2009-TT-BNNPTNT-tieu-chi-xac-dinh-va-phan-loai-rung-97079.aspx"),
            ("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://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Thong-tu-34-2009-TT-BNNPTNT-tieu-chi-xac-dinh-va-phan-loai-rung-97079.aspx"),
        ],
    },
    {
        "icon": "🗺️",
        "vi": "Bản đồ lâm nghiệp",
        "en": "Forestry Maps",
        "docs": [
            ("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",
             ""),
            ("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",
             ""),
        ],
    },
    {
        "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://vsqi.gov.vn/en/tcvn/tcvn-11567-1-2016"),
            ("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://vsqi.gov.vn/en/tcvn/tcvn-11567-2-2016"),
            ("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://vsqi.gov.vn/en/tcvn/tcvn-12509-1-2018"),
        ],
    },
    {
        "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://vsqi.gov.vn/en/tcvn/tcvn-14274-2025"),
            ("TCVN_2025_CapDuBao_ChayRung.pdf",
             "TCVN 2025 — Cấp dự báo cháy rừng",
             "TCVN 2025 — Forest fire forecast classification",
             "https://vsqi.gov.vn/en/tcvn"),
        ],
    },
    {
        "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://thuvienphapluat.vn/van-ban/Tai-nguyen-Moi-truong/Quyet-dinh-04-2004-QD-BNN-quy-che-khai-thac-go-lam-san-52430.aspx"),
            ("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://vsqi.gov.vn"),
            ("TCN_74_2006_PhanLoaiGoTron.doc",
             "04 TCN 74:2006 — Phân loại gỗ tròn",
             "04 TCN 74:2006 — Round timber classification",
             "https://luatvietnam.vn/nong-nghiep/tieu-chuan-nganh-04-tcn-74-2006-bo-nong-nghiep-va-phat-trien-nong-thon-177398-d5.html"),
            ("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://luatvietnam.vn/nong-nghiep/tieu-chuan-nganh-04-tcn-126-2006-bo-nong-nghiep-va-phat-trien-nong-thon-177439-d5.html"),
            ("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://luatvietnam.vn/nong-nghiep/tieu-chuan-nganh-04-tcn-132-2006-bo-nong-nghiep-va-phat-trien-nong-thon-177441-d5.html"),
            ("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://vsqi.gov.vn/en/tcvn/tcvn-13353-2021"),
            ("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://vsqi.gov.vn"),
        ],
    },
]


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() & ~Qt.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.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 = (
            "📄 = Mở file local  |  🌐 = Mở link online"
            if lang == "vi" else
            "📄 = Open local file  |  🌐 = Open online link"
        )
        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)

        # Close button
        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)
        root.addWidget(btn_close)

    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.NoFrame)

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

        for filename, vi_title, en_title, url in docs:
            title = vi_title if lang == "vi" else en_title
            filepath = os.path.join(_DOCS_DIR, filename)
            is_local = os.path.isfile(filepath)

            # Icon based on source type
            if is_local:
                ext = os.path.splitext(filename)[1].upper().replace(".", "")
                src_icon = "📄" if ext == "PDF" else "📝"
            else:
                src_icon = "🌐"

            btn = QPushButton(f"{src_icon}  {title}")
            btn.setFont(QFont("Segoe UI", 10))
            btn.setMinimumHeight(38)
            btn.setCursor(Qt.PointingHandCursor)

            if is_local:
                # Local file available — open with system app
                btn.setStyleSheet(
                    "QPushButton{text-align:left;padding:6px 12px;"
                    "background:#fff8e1;border:1px solid #ffe082;"
                    "border-radius:4px;}"
                    "QPushButton:hover{background:#fff3c4;"
                    "border-color:#ffc107;}"
                )
                tooltip = (
                    f"📄 File local: {filename}"
                    if lang == "vi" else
                    f"📄 Local file: {filename}"
                )
                btn.setToolTip(tooltip)
                btn.clicked.connect(
                    lambda checked, f=filepath: self._open_file(f)
                )
            else:
                # No local file — open online link
                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;}"
                )
                tooltip = (
                    f"🌐 Mở trực tuyến: {url}"
                    if lang == "vi" else
                    f"🌐 Open online: {url}"
                )
                btn.setToolTip(tooltip)
                btn.clicked.connect(
                    lambda checked, u=url: self._open_url(u)
                )

            inner.addWidget(btn)

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

    @staticmethod
    def _open_file(filepath):
        """Open a file with the system's default application."""
        QDesktopServices.openUrl(QUrl.fromLocalFile(filepath))

    @staticmethod
    def _open_url(url):
        """Open a URL in the system's default web browser."""
        QDesktopServices.openUrl(QUrl(url))
