import random
import frappe
from frappe.model.naming import parse_naming_series
from erpnext.selling.doctype.quotation.quotation import Quotation as OriginalQuotation

class Quotation(OriginalQuotation):
    def autoname(self):
        # Use selected naming series or default from meta
        naming_series_pattern = self.naming_series or frappe.get_meta(self.doctype).get_field("naming_series").options.split("\n")[0]

        # Step 1: Resolve dynamic placeholders (like .YYYY.) WITHOUT incrementing the counter
        prefix = parse_naming_series(naming_series_pattern)

        # Remove any trailing dash if it exists
        prefix = prefix.rstrip("-")

        # Step 2: Append a random 6-digit number
        random_part = str(random.randint(100_000, 999_999))  # 6-digit number
        name = f"{prefix}-{random_part}"

        # Step 3: Ensure name is unique
        while frappe.db.exists(self.doctype, name):
            random_part = str(random.randint(100_000, 999_999))  # 6-digit number
            name = f"{prefix}-{random_part}"

        self.name = name
