from __future__ import annotations

import sqlite3
import unittest
from pathlib import Path
from zipfile import ZipFile

from mais_humana.charts import matrix_heatmap_svg
from mais_humana.docx_writer import DocxDocument
from mais_humana.models import GeneratedFile, MatrixCell, MaturityLevel
from mais_humana.storage import connect, table_counts, upsert_files
from tests.helpers import make_tmp


class DocxChartsStorageTests(unittest.TestCase):
    def test_docx_writer_creates_valid_zip_parts(self) -> None:
        tmp = make_tmp()
        path = tmp / "sample.docx"
        doc = DocxDocument(title="Relatorio")
        doc.heading("Sintese", 2)
        doc.paragraph("Texto operacional")
        doc.bullet("Item validado")
        doc.table(("A", "B"), (("1", "2"),))
        doc.write(path)
        self.assertTrue(path.exists())
        with ZipFile(path) as archive:
            names = set(archive.namelist())
            self.assertIn("word/document.xml", names)
            self.assertIn("word/styles.xml", names)
            self.assertIn("word/numbering.xml", names)

    def test_chart_writer_outputs_svg_with_scores(self) -> None:
        tmp = make_tmp()
        cells = (
            MatrixCell(
                platform_id="identity",
                profile_id="administrador_empresa",
                score=88,
                maturity=MaturityLevel.READY_FOR_HUMAN,
                explanation="ok",
                strengths=("a",),
                gaps=("b",),
                evidence_refs=("README.md",),
            ),
        )
        path = matrix_heatmap_svg(tmp / "matrix.svg", cells)
        text = path.read_text(encoding="utf-8")
        self.assertIn("<svg", text)
        self.assertIn("identity", text)
        self.assertIn("88", text)

    def test_storage_upserts_file_semantics(self) -> None:
        tmp = make_tmp()
        db = tmp / "controle.sqlite"
        file = GeneratedFile(
            path="dados/snapshot.json",
            description="Snapshot",
            function="dados",
            file_type="json",
            changed_by="test",
            change_summary="criado",
            relation_to_order="ordem",
        )
        with connect(db) as conn:
            upsert_files(conn, (file,))
            upsert_files(conn, (file,))
            conn.commit()
        self.assertEqual(table_counts(db)["files"], 1)
        with sqlite3.connect(db) as conn:
            row = conn.execute("SELECT descricao FROM files WHERE caminho_arquivo=?", (file.path,)).fetchone()
        self.assertEqual(row[0], "Snapshot")


if __name__ == "__main__":
    unittest.main()
