import os
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta


class Dependency:
    def __init__(self, groupId, artifactId, version):
        self.groupId = groupId
        self.artifactId = artifactId
        self.version = version

    @staticmethod
    def of(md: 'Metadata'):
        return Dependency(md.groupId, md.artifactId, md.versioning.latest)

    def __str__(self):
        return f"{self.groupId}:{self.artifactId}:{self.version}"

    def getGradleKotlin(self):
        return f'implementation("{self.groupId}:{self.artifactId}:{self.version}")'

    def getGradle(self):
        return f"implementation '{self.groupId}:{self.artifactId}:{self.version}'"

    def getMaven(self):
        return f"""
<dependency>
    <groupId>{self.groupId}</groupId>
    <artifactId>{self.artifactId}</artifactId>
    <version>{self.version}</version>
</dependency>
"""


class Versions(dict):

    @property
    def version(self) -> list[str]:
        if type(self["version"]) == str:
            return [self["version"]]
        return self["version"]


class Versioning(dict):

    @property
    def latest(self):
        return self["latest"]

    @property
    def release(self):
        return self["release"]

    @property
    def versions(self) -> Versions:
        return Versions(self["versions"])

    @property
    def lastUpdated(self) -> datetime:
        return datetime.strptime(self["lastUpdated"], "%Y%m%d%H%M%S") + timedelta(hours=8)


class Metadata(dict):
    @property
    def groupId(self):
        return self["groupId"]

    @property
    def artifactId(self):
        return self["artifactId"]

    @property
    def versioning(self) -> Versioning:
        return Versioning(self["versioning"])


def xml_to_dict(xml_data):
    """将XML数据转换为字典"""

    def parse_element(element):
        """递归解析XML元素"""
        result = {}
        for child in element:
            if len(child) > 0:
                if child.tag in result:
                    if not isinstance(result[child.tag], list):
                        result[child.tag] = [result[child.tag]]
                    result[child.tag].append(parse_element(child))
                else:
                    result[child.tag] = parse_element(child)
            else:  # 如果是叶子节点
                if child.tag in result:  # 处理重复标签
                    if not isinstance(result[child.tag], list):
                        result[child.tag] = [result[child.tag]]
                    result[child.tag].append(child.text)
                else:
                    result[child.tag] = child.text
        return result

    if isinstance(xml_data, str):
        root = ET.fromstring(xml_data)
    elif isinstance(xml_data, ET.Element):
        root = xml_data
    else:
        raise TypeError("输入必须是XML字符串或Element对象")

    return {root.tag: parse_element(root)}


def getmaven_metadata_files(path='.'):
    """查找指定路径下所有的maven-metadata.xml文件"""
    metadata_files = []
    for root, dirs, files in os.walk(path):
        for file in files:
            if file == 'maven-metadata.xml':
                full_path = os.path.join(root, file)
                metadata_files.append(full_path)
    return metadata_files


def getdatas() -> list[Metadata]:
    d = []
    for metadata_file in getmaven_metadata_files():
        with open(metadata_file, 'r') as f:
            d.append(Metadata(xml_to_dict(f.read())["metadata"]))
    return d


if __name__ == '__main__':
    f = open('./update/README.MD','r',encoding='utf-8')
    readme = f.read()
    f.close()
    readme += "# Packs-Dependencys\n"

    for metadata in getdatas():
        readme += f"## {metadata.artifactId}\n"
        dep = Dependency.of(metadata)
        readme += f"### maven (pom.xml)\n"
        readme += f"```xml{dep.getMaven()}```\n"
        readme += f"### Gradle (Groovy DSL - build.gradle)\n"
        readme += f"```groovy\n{dep.getGradle()}\n```\n"
        readme += f"### Gradle (Kotlin DSL - build.gradle.kts)\n"
        readme += f"```kotlin\n{dep.getGradleKotlin()}\n```\n"



    f = open('README.MD','w',encoding='utf-8')
    f.write(readme)
    f.close()

