#!/usr/bin/env python3
import os
import re
import json
import datetime as dt
from pathlib import Path

PROJECT_ROOT = Path("/home/eddinala/public_html").resolve()

SCAN_DIRS = ["app", "routes", "config", "database", "resources"]
EXT_OK = {".php", ".blade.php", ".js", ".ts"}

RX_CCY = re.compile(r"\b(SYR|SYP)\b")
RX_CONDISH = re.compile(r"(if\s*\(|in_array\s*\(|switch\s*\(|case\s+|==|!=)", re.IGNORECASE)

MAX_LINES = 200
TOP_FILES = 80
SAMPLES_PER_FILE = 2

def now_ts() -> str:
    return dt.datetime.now().strftime("%Y%m%d_%H%M%S")

def rel(p: Path) -> str:
    try:
        return str(p.resolve().relative_to(PROJECT_ROOT))
    except Exception:
        return str(p)

def read_env(env_path: Path) -> dict:
    env = {}
    if not env_path.exists():
        return env
    for raw in env_path.read_text(encoding="utf-8", errors="ignore").splitlines():
        s = raw.strip()
        if not s or s.startswith("#") or "=" not in s:
            continue
        k, v = s.split("=", 1)
        env[k.strip()] = v.strip().strip('"').strip("'")
    return env

def scan_code():
    file_stats = []
    cond_lines = []
    total_hits = 0

    for d in SCAN_DIRS:
        base = PROJECT_ROOT / d
        if not base.exists():
            continue

        for f in base.rglob("*"):
            if not f.is_file():
                continue
            if f.suffix.lower() not in EXT_OK:
                continue

            try:
                lines = f.read_text(encoding="utf-8", errors="ignore").splitlines()
            except Exception:
                continue

            hits_in_file = 0
            samples = []
            for ln, line in enumerate(lines, start=1):
                if not RX_CCY.search(line):
                    continue

                hits_in_file += 1
                total_hits += 1

                if len(samples) < SAMPLES_PER_FILE:
                    txt = re.sub(r"\s{2,}", " ", line.strip())
                    if len(txt) > 360:
                        txt = txt[:360] + "..."
                    samples.append(f"L{ln}: {txt}")

                if len(cond_lines) < MAX_LINES and RX_CONDISH.search(line):
                    txt = re.sub(r"\s{2,}", " ", line.strip())
                    if len(txt) > 420:
                        txt = txt[:420] + "..."
                    cond_lines.append(f"[{len(cond_lines)+1}] {rel(f)}:L{ln} {txt}")

                if len(cond_lines) >= MAX_LINES and len(samples) >= SAMPLES_PER_FILE:
                    pass

            if hits_in_file > 0:
                file_stats.append({
                    "file": rel(f),
                    "hits": hits_in_file,
                    "samples": samples
                })

    file_stats.sort(key=lambda x: x["hits"], reverse=True)
    return {
        "total_hits": total_hits,
        "files_with_hits": len(file_stats),
        "top_files": file_stats[:TOP_FILES],
        "conditional_lines": cond_lines
    }

def db_snapshot(env: dict) -> dict:
    try:
        import pymysql
    except Exception:
        return {"error": "PyMySQL غير مثبت. نفّذ pip --user"}

    db = env.get("DB_DATABASE") or ""
    host = env.get("DB_HOST") or "127.0.0.1"
    port = int(env.get("DB_PORT") or "3306")
    user = env.get("DB_USERNAME") or ""
    password = env.get("DB_PASSWORD") or ""

    if not db:
        return {"error": "DB_DATABASE فارغ في ملف .env"}

    out = {}
    try:
        con = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            database=db,
            charset="utf8mb4",
            autocommit=True,
            cursorclass=pymysql.cursors.DictCursor
        )
        cur = con.cursor()

        def try_query(label, sql):
            try:
                cur.execute(sql)
                return cur.fetchall()
            except Exception as e:
                return {"error": f"{label}: {e}"}

        out["wallets_currency_code_distinct"] = try_query(
            "wallets distinct",
            "SELECT DISTINCT currency_code AS v FROM wallets ORDER BY currency_code"
        )
        out["accounts_currency_distinct"] = try_query(
            "accounts distinct",
            "SELECT DISTINCT currency AS v FROM accounts ORDER BY currency"
        )
        out["api_sources_currency_distinct"] = try_query(
            "api_sources distinct",
            "SELECT DISTINCT currency AS v FROM api_sources ORDER BY currency"
        )

        out["user_wallets_summary_by_currency"] = try_query(
            "user_wallets summary",
            """
            SELECT w.currency_code AS currency_code,
                   COUNT(*) AS rows_count,
                   COALESCE(SUM(uw.balance),0) AS sum_balance
            FROM user_wallets uw
            JOIN wallets w ON uw.wallet_id = w.id
            GROUP BY w.currency_code
            ORDER BY w.currency_code
            """
        )

        out["products_uses_new_lira_counts"] = try_query(
            "products uses_new_lira counts",
            """
            SELECT
              SUM(CASE WHEN uses_new_lira = 1 THEN 1 ELSE 0 END) AS true_count,
              SUM(CASE WHEN uses_new_lira IS NULL OR uses_new_lira = 0 THEN 1 ELSE 0 END) AS false_or_null_count
            FROM products
            """
        )

        cur.close()
        con.close()
    except Exception as e:
        return {"error": f"DB_CONNECT_OR_QUERY_ERROR: {e}"}

    return out

def write_md(path: Path, text: str):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8", newline="\n") as f:
        f.write(text if text.endswith("\n") else text + "\n")

def main():
    out_dir = PROJECT_ROOT / "currency_audit_out"
    out_file = out_dir / f"currency_audit_min_{now_ts()}.md"

    env = read_env(PROJECT_ROOT / ".env")
    code = scan_code()
    db = db_snapshot(env)

    write_md(out_file, "## Currency Minimal Audit")
    write_md(out_file, f"GeneratedAt: {dt.datetime.now()}")
    write_md(out_file, f"ProjectRoot: {PROJECT_ROOT}")
    write_md(out_file, "")

    write_md(out_file, "## Code Scan Summary")
    write_md(out_file, f"- TotalHits(SYR/SYP): {code['total_hits']}")
    write_md(out_file, f"- FilesWithHits: {code['files_with_hits']}")
    write_md(out_file, "")

    write_md(out_file, "## Top Files (hits + up to 2 samples)")
    write_md(out_file, "```")
    for i, item in enumerate(code["top_files"], start=1):
        write_md(out_file, f"[{i}] {item['file']} (hits={item['hits']})")
        for s in item["samples"]:
            write_md(out_file, f"  - {s}")
    write_md(out_file, "```")
    write_md(out_file, "")

    write_md(out_file, f"## Conditional-ish Lines (max {MAX_LINES})")
    write_md(out_file, "```")
    if not code["conditional_lines"]:
        write_md(out_file, "NO_HITS_FOUND")
    else:
        for line in code["conditional_lines"]:
            write_md(out_file, line)
    write_md(out_file, "```")
    write_md(out_file, "")

    write_md(out_file, "## DB Snapshots (small)")
    write_md(out_file, "```json")
    write_md(out_file, json.dumps(db, ensure_ascii=False, indent=2))
    write_md(out_file, "```")
    write_md(out_file, "")

    write_md(out_file, "## STATUS")
    write_md(out_file, "COMPLETED")

    print(f"DONE -> {out_file}")

if __name__ == "__main__":
    main()
