import random
import re
import frappe
from datetime import datetime
from frappe.model.naming import parse_naming_series
from erpnext.projects.doctype.project.project import Project as OriginalProject

class Project(OriginalProject):
    # Change naming covention to PROJ-2025-3812 where 3812 is a random number
    def autoname(self):
        # Use the series pattern from the doctype or meta
        naming_series_pattern = self.naming_series or frappe.get_meta(self.doctype).get_field("naming_series").options.split("\n")[0]

        # Resolve the naming pattern (e.g., PROJ-0001)
        parsed_prefix = parse_naming_series(naming_series_pattern)

        # Remove auto-number if present (e.g., strip -0001)
        clean_prefix = re.sub(r"[-_]?0*\d+$", "", parsed_prefix)

        # Get current year
        current_year = datetime.now().year

        # Generate 4-digit random number
        random_part = str(random.randint(1000, 9999))

        # Combine all parts
        name = f"{clean_prefix}-{current_year}-{random_part}"

        # Ensure uniqueness
        while frappe.db.exists(self.doctype, name):
            random_part = str(random.randint(1000, 9999))
            name = f"{clean_prefix}-{current_year}-{random_part}"

        self.name = name
