import os
import sys
import re
import subprocess




def main():
    # ---------- BASE PATH ----------
    project_path = os.getcwd()  # فرض می‌کنیم اسکریپت در ریشه پروژه اجرا میشه

    # ---------- VALIDATION ----------
    def get_valid_name(prompt):
        invalid_chars = r'[\\/:*?"<>|]'
        while True:
            name = input(prompt).strip()
            if not name:
                print("❌ Name cannot be empty.")
                continue
            if name in [".", ".."]:
                print("❌ Invalid name.")
                continue
            if re.search(invalid_chars, name):
                print("❌ Name contains invalid characters: \\ / : * ? \" < > |")
                continue
            # فاصله تبدیل به -
            name = name.replace(" ", "-")
            return name

    def list_files(folder, extension):
        """لیست فایل‌های با پسوند مشخص در یک پوشه"""
        if not os.path.exists(folder):
            print(f"❌ Folder does not exist: {folder}")
            return
        files = [f for f in os.listdir(folder) if f.endswith(extension)]
        if not files:
            print(f"No {extension} files found in {folder}")
        else:
            print(f"{extension.upper()} files in {folder}:")
            for i, file in enumerate(files, 1):
                print(f"{i}. {file}")
    def list_files(folder, extension):
        """لیست فایل‌های با پسوند مشخص در یک پوشه"""
        if not os.path.exists(folder):
            print(f"❌ Folder does not exist: {folder}")
            return
        files = [f for f in os.listdir(folder) if f.endswith(extension)]
        if not files:
            print(f"No {extension} files found in {folder}")
        else:
            print(f"{extension.upper()} files in {folder}:")
            for i, file in enumerate(files, 1):
                print(f"{i}. {file}")

    # ---------- COMMAND ----------
    if len(sys.argv) > 1:
        command = sys.argv[1]
    else:
        command = None
    # ---------- LIST COMMANDS ----------
    if command == "list-html":
        list_files(os.path.join(project_path, "pages"), ".html")
        sys.exit()

    elif command == "list-css":
        list_files(os.path.join(project_path, "css/pages"), ".css")
        sys.exit()

    elif command == "list-js":
        list_files(os.path.join(project_path, "js/modules"), ".js")
        sys.exit()

    # ---------- HTML TEMPLATE ----------
    def html_template(title, css_path, js_path):
        return f"""<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">
        <title>{title}</title>
        <link rel="stylesheet" href="{css_path}">
        <link rel="stylesheet" href="{css_path.replace('style.css', 'reset.css')}">
    </head>
    <body>
    
    <h1>{title}</h1>
    
    <script src="{js_path}"></script>
    </body>
    </html>"""

    # ---------- LINK FUNCTIONS ----------
    def link_css_to_index(css_file_name):
        index_html = os.path.join(project_path, "index.html")
        link_tag = f'<link rel="stylesheet" href="css/pages/{css_file_name}.css">'
        if os.path.exists(index_html):
            with open(index_html, "r", encoding="utf-8") as f:
                content = f.read()
            if link_tag not in content:
                content = content.replace("</head>", f"    {link_tag}\n</head>")
                with open(index_html, "w", encoding="utf-8") as f:
                    f.write(content)

    def link_js_to_index(js_file_name):
        index_html = os.path.join(project_path, "index.html")
        script_tag = f'<script src="js/modules/{js_file_name}.js"></script>'
        if os.path.exists(index_html):
            with open(index_html, "r", encoding="utf-8") as f:
                content = f.read()
            if script_tag not in content:
                index = content.rfind("</body>")
                if index != -1:
                    content = content[:index] + f"    {script_tag}\n" + content[index:]
                    with open(index_html, "w", encoding="utf-8") as f:
                        f.write(content)

    def link_css_to_html_file(css_file_name):
        pages_dir = os.path.join(project_path, "pages")
        html_files = [f for f in os.listdir(pages_dir) if f.endswith(".html")]

        if not html_files:
            return

        print("Available HTML files in pages/:")
        for i, file in enumerate(html_files):
            print(f"{i+1}. {file}")

        choice = input("Which HTML file should this CSS be linked to? (number): ")
        try:
            choice_index = int(choice) - 1
            if 0 <= choice_index < len(html_files):
                target_file = os.path.join(pages_dir, html_files[choice_index])
                link_tag = f'<link rel="stylesheet" href="../css/pages/{css_file_name}.css">'
                with open(target_file, "r", encoding="utf-8") as f:
                    content = f.read()
                if link_tag not in content:
                    content = content.replace("</head>", f"    {link_tag}\n</head>")
                    with open(target_file, "w", encoding="utf-8") as f:
                        f.write(content)
                    print(f"✅ Linked {css_file_name}.css to {html_files[choice_index]}")
        except ValueError:
            print("❌ Invalid input")

    def link_js_to_html_file(js_file_name):
        pages_dir = os.path.join(project_path, "pages")
        html_files = [f for f in os.listdir(pages_dir) if f.endswith(".html")]

        if not html_files:
            return

        print("Available HTML files in pages/:")
        for i, file in enumerate(html_files):
            print(f"{i+1}. {file}")

        choice = input("Which HTML file should this JS be linked to? (number): ")
        try:
            choice_index = int(choice) - 1
            if 0 <= choice_index < len(html_files):
                target_file = os.path.join(pages_dir, html_files[choice_index])
                script_tag = f'<script src="../js/modules/{js_file_name}.js"></script>'
                with open(target_file, "r", encoding="utf-8") as f:
                    content = f.read()
                if script_tag not in content:
                    index = content.rfind("</body>")
                    if index != -1:
                        content = content[:index] + f"    {script_tag}\n" + content[index:]
                        with open(target_file, "w", encoding="utf-8") as f:
                            f.write(content)
                        print(f"✅ Linked {js_file_name}.js to {html_files[choice_index]}")
        except ValueError:
            print("❌ Invalid input")

    # ---------- ADD-CSS ----------
    if command == "add-css":
        css_name = get_valid_name("CSS file name (without .css): ")
        css_path = os.path.join(project_path, "css", "pages", f"{css_name}.css")
        os.makedirs(os.path.dirname(css_path), exist_ok=True)
        with open(css_path, "w", encoding="utf-8") as f:
            f.write(f"/* {css_name}.css */")

        link_css_to_index(css_name)
        link_css_to_html_file(css_name)
        sys.exit()

    # ---------- ADD-JS ----------
    elif command == "add-js":
        js_name = get_valid_name("JS file name (without .js): ")
        js_path = os.path.join(project_path, "js/modules", f"{js_name}.js")
        os.makedirs(os.path.dirname(js_path), exist_ok=True)
        with open(js_path, "w", encoding="utf-8") as f:
            f.write(f"// {js_name}.js")

        link_js_to_index(js_name)
        link_js_to_html_file(js_name)
        sys.exit()

    # ---------- ADD-HTML ----------
    elif command == "add-html":
        html_name = get_valid_name("HTML file name (without .html): ")
        html_path = os.path.join(project_path, "pages", f"{html_name}.html")
        os.makedirs(os.path.dirname(html_path), exist_ok=True)
        with open(html_path, "w", encoding="utf-8") as f:
            f.write(f"""<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>{html_name}</title>
        <link rel="stylesheet" href="../css/style.css">
    </head>
    <body>
    <h1>{html_name}</h1>
    <script src="../js/main.js"></script>
    </body>
    </html>""")
        print(f"✅ HTML created: {html_path}")
        sys.exit()

    # ---------- INIT PROJECT ----------
    project_name = get_valid_name("Project name: ")
    site_title = get_valid_name("Website title (HTML <title>): ")

    extra_html = int(input("How many extra HTML pages do you want? "))
    extra_css = int(input("How many extra CSS files do you want? "))
    extra_js = int(input("How many extra JavaScript files do you want? "))

    use_scss = input("Do you want to use SCSS? (y/n): ").lower() == "y"

    project_path = os.path.join(project_path, project_name)

    # ---------- CREATE FOLDERS ----------
    folders = [
        "assets/img",
        "assets/fonts",
        "assets/icons",
        "css/pages",
        "js/modules",
        "pages"
    ]
    if use_scss:
        folders.append("scss")

    os.makedirs(project_path, exist_ok=True)
    for folder in folders:
        os.makedirs(os.path.join(project_path, folder), exist_ok=True)

    # ---------- HTML ----------
    with open(os.path.join(project_path, "index.html"), "w", encoding="utf-8") as f:
        f.write(html_template(site_title, "css/style.css", "js/main.js"))

    for i in range(extra_html):
        with open(os.path.join(project_path, "pages", f"page{i+1}.html"), "w", encoding="utf-8") as f:
            f.write(html_template(site_title, "../css/style.css", "../js/main.js"))

    # ---------- CSS ----------
    reset_css_content = """/* CSS Reset */
    *,
    *::before,
    *::after {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    html, body { height: 100%; }
    
    body { line-height: 1.5; font-family: sans-serif; }
    
    img, picture, video, canvas, svg { display: block; max-width: 100%; }
    
    input, button, textarea, select { font: inherit; }
    
    a { text-decoration: none; color: inherit; }
    """

    with open(os.path.join(project_path, "css", "reset.css"), "w") as f:
        f.write(reset_css_content)

    with open(os.path.join(project_path, "css", "style.css"), "w") as f:
        f.write("/* Main styles */\n")

    for i in range(extra_css):
        css_file = os.path.join(project_path, "css/pages", f"page{i+1}.css")
        with open(css_file, "w") as f:
            f.write("")
        link_css_to_index(f"page{i+1}")

    # ---------- JS ----------
    with open(os.path.join(project_path, "js", "main.js"), "w") as f:
        f.write("// Main JavaScript file\n")

    for i in range(extra_js):
        js_file = os.path.join(project_path, "js/modules", f"module{i+1}.js")
        with open(js_file, "w") as f:
            f.write("")
        link_js_to_index(f"module{i+1}")

    # ---------- SCSS ----------
    if use_scss:
        with open(os.path.join(project_path, "scss", "main.scss"), "w") as f:
            f.write("@import 'variables';\n@import 'mixins';")
        open(os.path.join(project_path, "scss", "_variables.scss"), "w").close()
        open(os.path.join(project_path, "scss", "_mixins.scss"), "w").close()

    # ---------- README ----------
    with open(os.path.join(project_path, "README.md"), "w", encoding="utf-8") as f:
        f.write(f"# {project_name}\n\n{site_title}")

    print("✅ Professional web project created successfully!")

if __name__ == "__main__":
    main()
