import shutil
from pathlib import Path

from app.core.postgres.erp_client import ErpDatabaseClient


def clean_filesystem():
    root = Path(r"c:\Projects\DSCons")
    # Delete files
    for f in [
        "cloudflared.log",
        "uvicorn.log",
        "uvicorn_err.log",
        "temp.js",
        "temp2.js",
        "script.vbs",
        "pytest.ini",
    ]:
        p = root / f
        if p.exists():
            p.unlink()
    # Delete dirs
    for d in [".pytest_cache", "logs", "scratch", "reports", "snapshots"]:
        p = root / d
        if p.exists() and p.is_dir():
            for child in p.iterdir():
                if child.is_file():
                    child.unlink()
                elif child.is_dir():
                    shutil.rmtree(child)
    # Clear pycache
    for p in root.rglob("__pycache__"):
        if "venv" not in str(p) and p.is_dir():
            shutil.rmtree(p)

    # Clear storage secure vault for test files
    vault = root / "storage" / "secure_vault"
    if vault.exists():
        for child in vault.iterdir():
            if (
                "TEST" in child.name.upper()
                or "SAMPLE" in child.name.upper()
                or "API_CAD" in child.name.upper()
            ):
                child.unlink()


def clean_database():
    try:
        db = ErpDatabaseClient()

        # Clean takeoffs
        takeoffs = db.list_drawing_takeoffs()
        for t in takeoffs:
            title = (
                t.get("filename")
                or t.get("drawing_name")
                or t.get("drawing_title")
                or ""
            )
            title_upper = title.upper()
            if any(
                x in title_upper
                for x in [
                    "TEST",
                    "SAMPLE",
                    "API_CAD",
                    "DWG_",
                    "FAST_UPLOAD",
                    "DIRECT_CONVERT",
                    "DRAWING_DEL",
                ]
            ):
                db.delete_drawing_takeoff(t["id"])

        # Clean projects
        projects = db.list_projects()
        for p in projects:
            if "TEST" in p["project_code"] or "TEST" in p["project_name"].upper():
                with db.get_connection() as conn, conn.cursor() as cur:
                    cur.execute("DELETE FROM projects WHERE id = %s", (p["id"],))
                    conn.commit()

    except Exception as e:
        print("DB Clean Error:", e)


if __name__ == "__main__":
    clean_filesystem()
    clean_database()
    print("Cleanup complete.")
