#!/usr/bin/env python3
import os
import re
from pathlib import Path


def version_parse(v):
    return tuple(map(int, (v.split("."))))


# Configuration
EN_FOLDER = "ISO27002-EN-2022"
EN_PATTERN = re.compile(r"ISO_27002_2022_([\d\.]+)_OT(.*)\.md")
EN_REF_PATTERN = re.compile(r"((?:\S+\s+){15})\(see ([\d\.]+)\)")


def main():
    # Build index of EN files by section number
    en_index = {}
    for filename in os.listdir(EN_FOLDER):
        if not filename.endswith(".md"):
            continue
        match = EN_PATTERN.match(filename)
        if match:
            section = match.group(1)
            title = match.group(2).strip()
            en_index[section] = {
                "filename": filename,
                "title": title,
                "display": f"{section} {title}",
            }

    report_content = []
    report_content.append("# ISO 27002:2022 EN Reference Mapping Report")
    report_content.append("")
    report_content.append(f"**Generated:** {os.popen('date -Iseconds').read().strip()}")
    report_content.append("")
    report_content.append("## Summary")

    total_references = 0
    matched = 0

    # Collect all entries first
    entries = []

    # Scan all EN files
    for filename in sorted(os.listdir(EN_FOLDER)):
        if not filename.endswith(".md"):
            continue
        file_path = os.path.join(EN_FOLDER, filename)

        # Extract source control number
        src_match = EN_PATTERN.match(filename)
        if not src_match:
            continue
        src_section = src_match.group(1)
        src_control = f"Control {src_section}"

        with open(file_path, "r", encoding="utf-8") as f:
            content = f.read()

        matches = EN_REF_PATTERN.findall(content)
        for preceding_text, ref in matches:
            total_references += 1
            ref_norm = ref.strip()

            preceding_words = " ".join(preceding_text.strip().split()[-10:])

            if ref_norm in en_index:
                probability = 100
                target_control = en_index[ref_norm]["display"]
                matched += 1
            else:
                probability = 0
                target_control = "NO MATCH"

            entries.append(
                [src_control, preceding_words, ref_norm, target_control, probability]
            )

    report_content.append(f"- Total references found: {total_references}")
    report_content.append(f"- Successfully matched: {matched}")
    report_content.append(
        f"- Match accuracy: {round(matched / total_references * 100, 1)}%"
    )
    report_content.append("")
    report_content.append(
        "| Source Control | Preceding 10 Words | Reference | Target Control | Match % |"
    )
    report_content.append(
        "|----------------|--------------------|-----------|----------------|---------|"
    )

    for entry in entries:
        report_content.append(
            f"| {entry[0]} | {entry[1]} | {entry[2]} | {entry[3]} | {entry[4]}% |"
        )

    with open("en_reference_mapping_report.md", "w", encoding="utf-8") as f:
        f.write("\n".join(report_content))

    print(f"Markdown report written to en_reference_mapping_report.md")
    print(
        f"Summary: {matched}/{total_references} references matched ({round(matched / total_references * 100, 1)}%)"
    )


if __name__ == "__main__":
    main()
