with open("app/services/drawing_takeoff_service.py", "r", encoding="utf-8") as f:
    code = f.read()

# Truncate at the first occurrence of get_drawing_takeoff_service
idx = code.find("def get_drawing_takeoff_service() -> DrawingTakeoffService:")
if idx != -1:
    code = code[:idx].rstrip() + "\n"

# Check if process_drawing_file exists
if "async def process_drawing_file" not in code:
    process_drawing_file_code = '''
    async def process_drawing_file(
        self,
        file_path: Path,
        filename: str,
        project_id: str | None = None,
        document_id: str | None = None,
        drawing_hint: str = "",
    ) -> dict[str, Any]:
        """Unified end-to-end entrypoint: creates takeoff record, runs pipeline, and returns full structured result."""
        created = self.create_pending_takeoff(
            file_path=file_path,
            filename=filename,
            project_id=project_id,
            document_id=document_id,
            drawing_hint=drawing_hint,
        )
        takeoff_id = created["id"]
        pipeline_result = await self.run_takeoff_pipeline(
            takeoff_id=takeoff_id,
            drawing_hint=drawing_hint,
        )

        takeoff = self._erp_client.get_drawing_takeoff(takeoff_id) or created
        items = self._erp_client.list_drawing_takeoff_items(takeoff_id) or []

        metrics = {
            "total_estimated_cost_vnd": float(takeoff.get("total_estimated_cost_vnd") or 0),
            "total_concrete_volume_m3": float(takeoff.get("total_concrete_volume_m3") or 0),
            "total_rebar_weight_tons": float(takeoff.get("total_rebar_weight_tons") or 0),
            "total_formwork_area_m2": float(takeoff.get("total_formwork_area_m2") or 0),
            "total_earthwork_volume_m3": float(takeoff.get("total_earthwork_volume_m3") or 0),
        }

        return {
            "status": "success",
            "takeoff": takeoff,
            "items": items,
            "metrics": metrics,
        }
'''
    code = code.rstrip() + "\n" + process_drawing_file_code

# Append the factory function at the end
code = (
    code.rstrip()
    + '''


_drawing_takeoff_service_instance: DrawingTakeoffService | None = None


def get_drawing_takeoff_service() -> DrawingTakeoffService:
    """Factory function to obtain DrawingTakeoffService singleton."""
    global _drawing_takeoff_service_instance
    if _drawing_takeoff_service_instance is None:
        _drawing_takeoff_service_instance = DrawingTakeoffService()
    return _drawing_takeoff_service_instance
'''
)

# Update create_pending_takeoff to ensure DWG- prefix
code = code.replace(
    "        drawing_code = filename",
    '        drawing_code = filename if (filename.startswith("DWG-") or filename.startswith("DWG_")) else f"DWG-{filename}"',
)
code = code.replace(
    '            "drawing_code": filename,',
    '            "drawing_code": filename if (filename.startswith("DWG-") or filename.startswith("DWG_")) else f"DWG-{filename}",',
)

# Enhance _render_cad_with_aspose to extract DXF entities via ezdxf
dxf_extract_snippet = """        extracted_lines = []
        if str(file_path).lower().endswith(".dxf"):
            try:
                import ezdxf
                doc = ezdxf.readfile(str(file_path))
                msp = doc.modelspace()
                for entity in msp:
                    raw_txt = ""
                    if entity.dxftype() == "TEXT":
                        raw_txt = entity.dxf.text if hasattr(entity.dxf, "text") else ""
                    elif entity.dxftype() == "MTEXT":
                        raw_txt = entity.plain_text() if hasattr(entity, "plain_text") else getattr(entity, "text", "")
                    if raw_txt:
                        clean = VietnameseCadFontTranscoder.auto_transcode_cad_text(raw_txt)
                        if clean:
                            extracted_lines.append(clean)
            except Exception:
                pass"""

code = code.replace("        extracted_lines = []", dxf_extract_snippet, 1)

# Enhance run_takeoff_pipeline file extension dispatching
old_extract = """            # Extraction
            ext_pages = self.extract_dwg_text_and_preview(file_path_str)"""
new_extract = """            # Extraction based on file extension
            ext = Path(file_path_str).suffix.lower()
            if ext == ".dwg":
                ext_pages = self.extract_dwg_text_and_preview(file_path_str)
            elif ext == ".dxf":
                ext_pages = self.render_dxf_to_images(file_path_str)
            elif ext == ".pdf":
                ext_pages = self.render_pdf_to_images(Path(file_path_str), max_pages=4, dpi=150)
            else:
                ext_pages = self.render_pdf_to_images(Path(file_path_str), max_pages=1, dpi=150)"""

code = code.replace(old_extract, new_extract)

with open("app/services/drawing_takeoff_service.py", "w", encoding="utf-8") as f:
    f.write(code)

print("Updated drawing_takeoff_service.py successfully!")
