from pathlib import Path

from scripts.production_preflight import (
    REQUIRED_PROTECTED_FILES,
    REQUIRED_SECRET_FILES,
    check_environment,
    parse_env_file,
)


def production_values(tls_dir: Path) -> dict[str, str]:
    return {
        "APP_ENV": "production",
        "APP_BASE_URL": "https://hayva.company.tld",
        "HAYVA_TLS_DIR": str(tls_dir),
        "COMPUTE_PROVIDER": "libvirt_gateway",
        "COMPUTE_PROVIDER_URL": "https://compute.internal.company",
        "DATABASE_URL": (
            "postgresql+asyncpg://hayva_app:strong-runtime-secret@postgres:5432/hayva"
        ),
        "DATABASE_MIGRATION_URL": (
            "postgresql+asyncpg://hayva_migrator:strong-migration-secret@postgres:5432/hayva"
        ),
        "POSTGRES_DB": "hayva",
        "POSTGRES_USER": "hayva_migrator",
        "POSTGRES_PASSWORD": "strong-migration-secret",
        "POSTGRES_RUNTIME_USER": "hayva_app",
        "POSTGRES_RUNTIME_PASSWORD": "strong-runtime-secret",
        "REDIS_URL": "redis://hayva:strong-redis-secret@redis:6379/0",
        "OPENAI_MODEL": "owner-approved-model",
    }


def create_protected_files(root: Path, tls_dir: Path) -> None:
    tls_dir.mkdir(parents=True)
    for filename in ("fullchain.pem", "privkey.pem"):
        (tls_dir / filename).write_text("test-certificate-material", encoding="utf-8")
    for relative in REQUIRED_SECRET_FILES:
        path = root / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        value = "s" * 40
        if relative == "secrets/redis/users.acl":
            value = "user hayva on >strong-redis-secret ~* +@all\n"
        path.write_text(value, encoding="utf-8")
        path.chmod(0o600)
    for relative in REQUIRED_PROTECTED_FILES:
        path = root / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text("disabled\n", encoding="utf-8")
        path.chmod(0o600)


def test_production_preflight_accepts_coherent_protected_configuration(tmp_path):
    tls_dir = tmp_path / "tls"
    create_protected_files(tmp_path, tls_dir)
    assert check_environment(production_values(tls_dir), tmp_path) == []


def test_production_preflight_rejects_placeholders_shared_roles_and_insecure_origins(tmp_path):
    tls_dir = tmp_path / "tls"
    create_protected_files(tmp_path, tls_dir)
    values = production_values(tls_dir)
    values.update({
        "APP_ENV": "development",
        "APP_BASE_URL": "http://localhost:8080",
        "COMPUTE_PROVIDER": "unconfigured",
        "POSTGRES_RUNTIME_USER": values["POSTGRES_USER"],
    })
    errors = check_environment(values, tmp_path)
    assert any("APP_ENV" in error for error in errors)
    assert any("public HTTPS" in error for error in errors)
    assert any("real VM gateway" in error for error in errors)
    assert any("identities must differ" in error for error in errors)


def test_env_parser_rejects_duplicate_or_malformed_keys(tmp_path):
    env_file = tmp_path / ".env"
    env_file.write_text("APP_ENV=production\nAPP_ENV=development\ninvalid line\n", encoding="utf-8")
    values, errors = parse_env_file(env_file)
    assert values == {"APP_ENV": "production"}
    assert len(errors) == 2
