import os
import tempfile
import uuid
from functools import wraps
from pathlib import Path

from flask import Flask, request, render_template, send_file, abort, Response

from audit_atomicat import run as run_audit

app = Flask(__name__)

# Ajuste se seus zips forem maiores que 300 MB.
app.config["MAX_CONTENT_LENGTH"] = 300 * 1024 * 1024

OUTPUT_ROOT = Path(tempfile.gettempdir()) / "atomicat_audit_outputs"
OUTPUT_ROOT.mkdir(exist_ok=True)

# Login simples pra quem tem o link. Troque isso via variavel de ambiente
# no painel do cPanel (Setup Python App > Environment variables), NAO deixe
# o valor padrao em producao.
APP_USER = os.environ.get("AUDIT_APP_USER", "lever")
APP_PASS = os.environ.get("AUDIT_APP_PASS", "cR9522^)A'EF0c+D")


def check_auth(username, password):
    return username == APP_USER and password == APP_PASS


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return Response(
                "Acesso restrito. Peca o usuario/senha pra quem administra essa ferramenta.",
                401,
                {"WWW-Authenticate": 'Basic realm="Auditoria Atomicat"'},
            )
        return f(*args, **kwargs)

    return decorated


@app.route("/", methods=["GET"])
@requires_auth
def index():
    return render_template("index.html")


@app.route("/process", methods=["POST"])
@requires_auth
def process():
    zip_file = request.files.get("zip_file")
    legal_zip_file = request.files.get("legal_zip_file")
    domain = (request.form.get("domain") or "").strip()
    old_domain = (request.form.get("old_domain") or "").strip() or "go-xarion.site"
    keep_telemetry = request.form.get("keep_telemetry") == "on"
    company_page = request.form.get("company_page") == "on"
    company_page_dir = (request.form.get("company_page_dir") or "").strip() or "empresa"
    company_link_text = (request.form.get("company_link_text") or "").strip() or "Dados da Empresa"
    company_overrides = {
        "name": (request.form.get("company_name") or "").strip(),
        "address": (request.form.get("company_address") or "").strip(),
        "phone": (request.form.get("company_phone") or "").strip(),
        "email": (request.form.get("company_email") or "").strip(),
    }

    if not zip_file or zip_file.filename == "":
        return render_template("index.html", error="Envie o zip exportado da Atomicat.")
    if not domain:
        return render_template("index.html", error="Informe o dominio real dessa pagina.")

    job_id = uuid.uuid4().hex[:12]
    job_dir = OUTPUT_ROOT / job_id
    job_dir.mkdir(parents=True, exist_ok=True)

    input_path = job_dir / "entrada.zip"
    zip_file.save(input_path)

    legal_zip_path = None
    if legal_zip_file and legal_zip_file.filename:
        legal_zip_path = job_dir / "legal.zip"
        legal_zip_file.save(legal_zip_path)

    output_path = job_dir / "saida.zip"

    try:
        report = run_audit(
            input_zip=str(input_path),
            output_zip=str(output_path),
            domain=domain,
            old_domain=old_domain,
            assets_dir="assets",
            cdn_host="media.atomicatmedia.net",
            telemetry_host="apido.atomicat-api.com",
            keep_telemetry=keep_telemetry,
            report_only=False,
            legal_zip=str(legal_zip_path) if legal_zip_path else None,
            company_page=company_page,
            company_page_dir=company_page_dir,
            company_link_text=company_link_text,
            company_overrides=company_overrides,
        )
    except Exception as e:  # noqa: BLE001
        return render_template("index.html", error=f"Erro ao processar: {e}")

    return render_template(
        "result.html",
        report_text=report.summary(),
        job_id=job_id,
    )


@app.route("/download/<job_id>")
@requires_auth
def download(job_id):
    if not job_id.isalnum():
        abort(404)
    output_path = OUTPUT_ROOT / job_id / "saida.zip"
    if not output_path.exists():
        abort(404)
    return send_file(output_path, as_attachment=True, download_name="saida.zip")


if __name__ == "__main__":
    app.run(debug=False, host="0.0.0.0", port=5000)
